context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // StringUtil.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; using System.Text.RegularExpressions; namespace Hyena { public static class StringUtil { private static CompareOptions compare_options = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth; public static int RelaxedIndexOf (string haystack, string needle) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf (haystack, needle, compare_options); } public static int RelaxedCompare (string a, string b) { if (a == null && b == null) { return 0; } else if (a != null && b == null) { return 1; } else if (a == null && b != null) { return -1; } int a_offset = a.StartsWith ("the ") ? 4 : 0; int b_offset = b.StartsWith ("the ") ? 4 : 0; return CultureInfo.CurrentCulture.CompareInfo.Compare (a, a_offset, a.Length - a_offset, b, b_offset, b.Length - b_offset, compare_options); } public static string CamelCaseToUnderCase (string s) { return CamelCaseToUnderCase (s, '_'); } private static Regex camelcase = new Regex ("([A-Z]{1}[a-z]+)", RegexOptions.Compiled); public static string CamelCaseToUnderCase (string s, char underscore) { if (String.IsNullOrEmpty (s)) { return null; } StringBuilder undercase = new StringBuilder (); string [] tokens = camelcase.Split (s); for (int i = 0; i < tokens.Length; i++) { if (tokens[i] == String.Empty) { continue; } undercase.Append (tokens[i].ToLower (System.Globalization.CultureInfo.InvariantCulture)); if (i < tokens.Length - 2) { undercase.Append (underscore); } } return undercase.ToString (); } public static string UnderCaseToCamelCase (string s) { if (String.IsNullOrEmpty (s)) { return null; } StringBuilder builder = new StringBuilder (); for (int i = 0, n = s.Length, b = -1; i < n; i++) { if (b < 0 && s[i] != '_') { builder.Append (Char.ToUpper (s[i])); b = i; } else if (s[i] == '_' && i + 1 < n && s[i + 1] != '_') { if (builder.Length > 0 && Char.IsUpper (builder[builder.Length - 1])) { builder.Append (Char.ToLower (s[i + 1])); } else { builder.Append (Char.ToUpper (s[i + 1])); } i++; b = i; } else if (s[i] != '_') { builder.Append (Char.ToLower (s[i])); b = i; } } return builder.ToString (); } public static string RemoveNewlines (string input) { if (input != null) { return input.Replace ("\r\n", String.Empty).Replace ("\n", String.Empty); } return null; } private static Regex tags = new Regex ("<[^>]+>", RegexOptions.Compiled | RegexOptions.Multiline); public static string RemoveHtml (string input) { if (input == null) { return input; } return tags.Replace (input, String.Empty); } public static string DoubleToTenthsPrecision (double num) { return DoubleToTenthsPrecision (num, false); } public static string DoubleToTenthsPrecision (double num, bool always_decimal) { return DoubleToTenthsPrecision (num, always_decimal, NumberFormatInfo.CurrentInfo); } public static string DoubleToTenthsPrecision (double num, bool always_decimal, IFormatProvider provider) { num = Math.Round (num, 1, MidpointRounding.ToEven); return String.Format (provider, !always_decimal && num == (int)num ? "{0:N0}" : "{0:N1}", num); } // This method helps us pluralize doubles. Probably a horrible i18n idea. public static int DoubleToPluralInt (double num) { if (num == (int)num) return (int)num; else return (int)num + 1; } // A mapping of non-Latin characters to be considered the same as // a Latin equivalent. private static Dictionary<char, char> BuildSpecialCases () { Dictionary<char, char> dict = new Dictionary<char, char> (); dict['\u00f8'] = 'o'; dict['\u0142'] = 'l'; return dict; } private static Dictionary<char, char> searchkey_special_cases = BuildSpecialCases (); // Removes accents from Latin characters, and some kinds of punctuation. public static string SearchKey (string val) { if (String.IsNullOrEmpty (val)) { return val; } val = val.ToLower (); StringBuilder sb = new StringBuilder (); UnicodeCategory category; bool previous_was_letter = false; bool got_space = false; // Normalizing to KD splits into (base, combining) so we can check for letters // and then strip off any NonSpacingMarks following them foreach (char orig_c in val.TrimStart ().Normalize (NormalizationForm.FormKD)) { // Check for a special case *before* whitespace. This way, if // a special case is ever added that maps to ' ' or '\t', it // won't cause a run of whitespace in the result. char c = orig_c; if (searchkey_special_cases.ContainsKey (c)) { c = searchkey_special_cases[c]; } if (c == ' ' || c == '\t') { got_space = true; continue; } category = Char.GetUnicodeCategory (c); if (category == UnicodeCategory.OtherPunctuation) { // Skip punctuation } else if (!(previous_was_letter && category == UnicodeCategory.NonSpacingMark)) { if (got_space) { sb.Append (" "); got_space = false; } sb.Append (c); } // Can ignore A-Z because we've already lowercased the char previous_was_letter = Char.IsLetter (c); } string result = sb.ToString (); try { result = result.Normalize (NormalizationForm.FormKC); } catch { // FIXME: work-around, see http://bugzilla.gnome.org/show_bug.cgi?id=590478 } return result; } private static Regex invalid_path_regex = BuildInvalidPathRegex (); private static Regex BuildInvalidPathRegex () { char [] invalid_path_characters = new char [] { // Control characters: there's no reason to ever have one of these in a track name anyway, // and they're invalid in all Windows filesystems. '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F', // Invalid in FAT32 / NTFS: " \ / : * | ? < > // Invalid in HFS : // Invalid in ext3 / '"', '\\', '/', ':', '*', '|', '?', '<', '>' }; string regex_str = "["; for (int i = 0; i < invalid_path_characters.Length; i++) { regex_str += "\\" + invalid_path_characters[i]; } regex_str += "]+"; return new Regex (regex_str, RegexOptions.Compiled); } private static CompareInfo culture_compare_info = CultureInfo.CurrentCulture.CompareInfo; public static byte[] SortKey (string orig) { if (orig == null) { return null; } return culture_compare_info.GetSortKey (orig, CompareOptions.IgnoreCase).KeyData; } private static readonly char[] escape_path_trim_chars = new char[] {'.', '\x20'}; public static string EscapeFilename (string input) { if (input == null) return ""; // Remove leading and trailing dots and spaces. input = input.Trim (escape_path_trim_chars); return invalid_path_regex.Replace (input, "_"); } public static string EscapePath (string input) { if (input == null) return ""; // This method should be called before the full path is constructed. if (Path.IsPathRooted (input)) { return input; } StringBuilder builder = new StringBuilder (); foreach (string name in input.Split (Path.DirectorySeparatorChar)) { // Escape the directory or the file name. string escaped = EscapeFilename (name); // Skip empty names. if (escaped.Length > 0) { builder.Append (escaped); builder.Append (Path.DirectorySeparatorChar); } } // Chop off the last character. if (builder.Length > 0) { builder.Length--; } return builder.ToString (); } public static string MaybeFallback (string input, string fallback) { string trimmed = input == null ? null : input.Trim (); return String.IsNullOrEmpty (trimmed) ? fallback : trimmed; } public static uint SubstringCount (string haystack, string needle) { if (String.IsNullOrEmpty (haystack) || String.IsNullOrEmpty (needle)) { return 0; } int position = 0; uint count = 0; while (true) { int index = haystack.IndexOf (needle, position); if (index < 0) { return count; } count++; position = index + 1; } } private static readonly char[] escaped_like_chars = new char[] {'\\', '%', '_'}; public static string EscapeLike (string s) { if (s.IndexOfAny (escaped_like_chars) != -1) { return s.Replace (@"\", @"\\").Replace ("%", @"\%").Replace ("_", @"\_"); } return s; } } }
// // SecurityPermissionAttributeTest.cs - // NUnit Test Cases for SecurityPermissionAttribute // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // 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 NUnit.Framework; using System; using System.Security; using System.Security.Permissions; namespace MonoTests.System.Security.Permissions { [TestFixture] public class SecurityPermissionAttributeTest { [Test] public void Default () { SecurityPermissionAttribute a = new SecurityPermissionAttribute (SecurityAction.Assert); Assert.IsFalse (a.Assertion, "Assertion"); #if NET_2_0 Assert.IsFalse (a.BindingRedirects, "BindingRedirects"); #endif Assert.IsFalse (a.ControlAppDomain, "ControlAppDomain"); Assert.IsFalse (a.ControlDomainPolicy, "ControlDomainPolicy"); Assert.IsFalse (a.ControlEvidence, "ControlEvidence"); Assert.IsFalse (a.ControlPolicy, "ControlPolicy"); Assert.IsFalse (a.ControlPrincipal, "ControlPrincipal"); Assert.IsFalse (a.ControlThread, "ControlThread"); Assert.IsFalse (a.Execution, "Execution"); Assert.IsFalse (a.Infrastructure, "Infrastructure"); Assert.IsFalse (a.RemotingConfiguration, "RemotingConfiguration"); Assert.IsFalse (a.SerializationFormatter, "SerializationFormatter"); Assert.IsFalse (a.SkipVerification, "SkipVerification"); Assert.IsFalse (a.UnmanagedCode, "UnmanagedCode"); Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags"); Assert.AreEqual (a.ToString (), a.TypeId.ToString (), "TypeId"); Assert.IsFalse (a.Unrestricted, "Unrestricted"); SecurityPermission perm = (SecurityPermission) a.CreatePermission (); Assert.AreEqual (SecurityPermissionFlag.NoFlags, perm.Flags, "CreatePermission.Flags"); } [Test] public void Action () { SecurityPermissionAttribute a = new SecurityPermissionAttribute (SecurityAction.Assert); Assert.AreEqual (SecurityAction.Assert, a.Action, "Action=Assert"); a.Action = SecurityAction.Demand; Assert.AreEqual (SecurityAction.Demand, a.Action, "Action=Demand"); a.Action = SecurityAction.Deny; Assert.AreEqual (SecurityAction.Deny, a.Action, "Action=Deny"); a.Action = SecurityAction.InheritanceDemand; Assert.AreEqual (SecurityAction.InheritanceDemand, a.Action, "Action=InheritanceDemand"); a.Action = SecurityAction.LinkDemand; Assert.AreEqual (SecurityAction.LinkDemand, a.Action, "Action=LinkDemand"); a.Action = SecurityAction.PermitOnly; Assert.AreEqual (SecurityAction.PermitOnly, a.Action, "Action=PermitOnly"); a.Action = SecurityAction.RequestMinimum; Assert.AreEqual (SecurityAction.RequestMinimum, a.Action, "Action=RequestMinimum"); a.Action = SecurityAction.RequestOptional; Assert.AreEqual (SecurityAction.RequestOptional, a.Action, "Action=RequestOptional"); a.Action = SecurityAction.RequestRefuse; Assert.AreEqual (SecurityAction.RequestRefuse, a.Action, "Action=RequestRefuse"); #if NET_2_0 a.Action = SecurityAction.DemandChoice; Assert.AreEqual (SecurityAction.DemandChoice, a.Action, "Action=DemandChoice"); a.Action = SecurityAction.InheritanceDemandChoice; Assert.AreEqual (SecurityAction.InheritanceDemandChoice, a.Action, "Action=InheritanceDemandChoice"); a.Action = SecurityAction.LinkDemandChoice; Assert.AreEqual (SecurityAction.LinkDemandChoice, a.Action, "Action=LinkDemandChoice"); #endif } [Test] public void Action_Invalid () { SecurityPermissionAttribute a = new SecurityPermissionAttribute ((SecurityAction)Int32.MinValue); // no validation in attribute } private SecurityPermissionAttribute Empty () { SecurityPermissionAttribute a = new SecurityPermissionAttribute (SecurityAction.Assert); a.Assertion = false; #if NET_2_0 a.BindingRedirects = false; #endif a.ControlAppDomain = false; a.ControlDomainPolicy = false; a.ControlEvidence = false; a.ControlPolicy = false; a.ControlPrincipal = false; a.ControlThread = false; a.Execution = false; a.Infrastructure = false; a.RemotingConfiguration = false; a.SerializationFormatter = false; a.SkipVerification = false; a.UnmanagedCode = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags"); return a; } [Test] public void Assertion () { SecurityPermissionAttribute a = Empty (); a.Assertion = true; Assert.AreEqual (SecurityPermissionFlag.Assertion, a.Flags, "Flags=Assertion"); a.Assertion = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } #if NET_2_0 [Test] public void BindingRedirects () { SecurityPermissionAttribute a = Empty (); a.BindingRedirects = true; Assert.AreEqual (SecurityPermissionFlag.BindingRedirects, a.Flags, "Flags=BindingRedirects"); a.BindingRedirects = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } #endif [Test] public void ControlAppDomain () { SecurityPermissionAttribute a = Empty (); a.ControlAppDomain = true; Assert.AreEqual (SecurityPermissionFlag.ControlAppDomain, a.Flags, "Flags=ControlAppDomain"); a.ControlAppDomain = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void ControlDomainPolicy () { SecurityPermissionAttribute a = Empty (); a.ControlDomainPolicy = true; Assert.AreEqual (SecurityPermissionFlag.ControlDomainPolicy, a.Flags, "Flags=ControlDomainPolicy"); a.ControlDomainPolicy = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void ControlEvidence () { SecurityPermissionAttribute a = Empty (); a.ControlEvidence = true; Assert.AreEqual (SecurityPermissionFlag.ControlEvidence, a.Flags, "Flags=ControlEvidence"); a.ControlEvidence = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void ControlPolicy () { SecurityPermissionAttribute a = Empty (); a.ControlPolicy = true; Assert.AreEqual (SecurityPermissionFlag.ControlPolicy, a.Flags, "Flags=ControlPolicy"); a.ControlPolicy = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void ControlPrincipal () { SecurityPermissionAttribute a = Empty (); a.ControlPrincipal = true; Assert.AreEqual (SecurityPermissionFlag.ControlPrincipal, a.Flags, "Flags=ControlPrincipal"); a.ControlPrincipal = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void ControlThread () { SecurityPermissionAttribute a = Empty (); a.ControlThread = true; Assert.AreEqual (SecurityPermissionFlag.ControlThread, a.Flags, "Flags=ControlThread"); a.ControlThread = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void Execution () { SecurityPermissionAttribute a = Empty (); a.Execution = true; Assert.AreEqual (SecurityPermissionFlag.Execution, a.Flags, "Flags=Execution"); a.Execution = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void Infrastructure () { SecurityPermissionAttribute a = Empty (); a.Infrastructure = true; Assert.AreEqual (SecurityPermissionFlag.Infrastructure, a.Flags, "Flags=Infrastructure"); a.Infrastructure = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void RemotingConfiguration () { SecurityPermissionAttribute a = Empty (); a.RemotingConfiguration = true; Assert.AreEqual (SecurityPermissionFlag.RemotingConfiguration, a.Flags, "Flags=RemotingConfiguration"); a.RemotingConfiguration = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void SerializationFormatter () { SecurityPermissionAttribute a = Empty (); a.SerializationFormatter = true; Assert.AreEqual (SecurityPermissionFlag.SerializationFormatter, a.Flags, "Flags=SerializationFormatter"); a.SerializationFormatter = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void SkipVerification () { SecurityPermissionAttribute a = Empty (); a.SkipVerification = true; Assert.AreEqual (SecurityPermissionFlag.SkipVerification, a.Flags, "Flags=SkipVerification"); a.SkipVerification = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void UnmanagedCode () { SecurityPermissionAttribute a = Empty (); a.UnmanagedCode = true; Assert.AreEqual (SecurityPermissionFlag.UnmanagedCode, a.Flags, "Flags=UnmanagedCode"); a.UnmanagedCode = false; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Flags=NoFlags"); } [Test] public void Unrestricted () { SecurityPermissionAttribute a = new SecurityPermissionAttribute (SecurityAction.Assert); a.Unrestricted = true; Assert.AreEqual (SecurityPermissionFlag.NoFlags, a.Flags, "Unrestricted"); SecurityPermission perm = (SecurityPermission) a.CreatePermission (); Assert.AreEqual (SecurityPermissionFlag.AllFlags, perm.Flags, "CreatePermission.Flags"); } [Test] public void Flags () { SecurityPermissionAttribute a = new SecurityPermissionAttribute (SecurityAction.Assert); a.Flags = SecurityPermissionFlag.Assertion; Assert.IsTrue (a.Assertion, "Assertion"); #if NET_2_0 a.Flags |= SecurityPermissionFlag.BindingRedirects; Assert.IsTrue (a.BindingRedirects, "BindingRedirects"); #endif a.Flags |= SecurityPermissionFlag.ControlAppDomain; Assert.IsTrue (a.ControlAppDomain, "ControlAppDomain"); a.Flags |= SecurityPermissionFlag.ControlDomainPolicy; Assert.IsTrue (a.ControlDomainPolicy, "ControlDomainPolicy"); a.Flags |= SecurityPermissionFlag.ControlEvidence; Assert.IsTrue (a.ControlEvidence, "ControlEvidence"); a.Flags |= SecurityPermissionFlag.ControlPolicy; Assert.IsTrue (a.ControlPolicy, "ControlPolicy"); a.Flags |= SecurityPermissionFlag.ControlPrincipal; Assert.IsTrue (a.ControlPrincipal, "ControlPrincipal"); a.Flags |= SecurityPermissionFlag.ControlThread; Assert.IsTrue (a.ControlThread, "ControlThread"); a.Flags |= SecurityPermissionFlag.Execution; Assert.IsTrue (a.Execution, "Execution"); a.Flags |= SecurityPermissionFlag.Infrastructure; Assert.IsTrue (a.Infrastructure, "Infrastructure"); a.Flags |= SecurityPermissionFlag.RemotingConfiguration; Assert.IsTrue (a.RemotingConfiguration, "RemotingConfiguration"); a.Flags |= SecurityPermissionFlag.SerializationFormatter; Assert.IsTrue (a.SerializationFormatter, "SerializationFormatter"); a.Flags |= SecurityPermissionFlag.SkipVerification; Assert.IsTrue (a.SkipVerification, "SkipVerification"); a.Flags |= SecurityPermissionFlag.UnmanagedCode; Assert.IsTrue (a.UnmanagedCode, "UnmanagedCode"); Assert.IsFalse (a.Unrestricted, "Unrestricted"); a.Flags &= ~SecurityPermissionFlag.Assertion; Assert.IsFalse (a.Assertion, "Assertion-False"); #if NET_2_0 a.Flags &= ~SecurityPermissionFlag.BindingRedirects; Assert.IsFalse (a.BindingRedirects, "BindingRedirects-False"); #endif a.Flags &= ~SecurityPermissionFlag.ControlAppDomain; Assert.IsFalse (a.ControlAppDomain, "ControlAppDomain-False"); a.Flags &= ~SecurityPermissionFlag.ControlDomainPolicy; Assert.IsFalse (a.ControlDomainPolicy, "ControlDomainPolicy-False"); a.Flags &= ~SecurityPermissionFlag.ControlEvidence; Assert.IsFalse (a.ControlEvidence, "ControlEvidence-False"); a.Flags &= ~SecurityPermissionFlag.ControlPolicy; Assert.IsFalse (a.ControlPolicy, "ControlPolicy-False"); a.Flags &= ~SecurityPermissionFlag.ControlPrincipal; Assert.IsFalse (a.ControlPrincipal, "ControlPrincipal-False"); a.Flags &= ~SecurityPermissionFlag.ControlThread; Assert.IsFalse (a.ControlThread, "ControlThread-False"); a.Flags &= ~SecurityPermissionFlag.Execution; Assert.IsFalse (a.Execution, "Execution-False"); a.Flags &= ~SecurityPermissionFlag.Infrastructure; Assert.IsFalse (a.Infrastructure, "Infrastructure-False"); a.Flags &= ~SecurityPermissionFlag.RemotingConfiguration; Assert.IsFalse (a.RemotingConfiguration, "RemotingConfiguration-False"); a.Flags &= ~SecurityPermissionFlag.SerializationFormatter; Assert.IsFalse (a.SerializationFormatter, "SerializationFormatter-False"); a.Flags &= ~SecurityPermissionFlag.SkipVerification; Assert.IsFalse (a.SkipVerification, "SkipVerification-False"); a.Flags &= ~SecurityPermissionFlag.UnmanagedCode; } [Test] public void Attributes () { Type t = typeof (SecurityPermissionAttribute); Assert.IsTrue (t.IsSerializable, "IsSerializable"); object[] attrs = t.GetCustomAttributes (typeof (AttributeUsageAttribute), false); Assert.AreEqual (1, attrs.Length, "AttributeUsage"); AttributeUsageAttribute aua = (AttributeUsageAttribute)attrs [0]; Assert.IsTrue (aua.AllowMultiple, "AllowMultiple"); Assert.IsFalse (aua.Inherited, "Inherited"); AttributeTargets at = (AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method); Assert.AreEqual (at, aua.ValidOn, "ValidOn"); } } }
using System; using System.Collections.Generic; namespace SharpLua.LASM { /// <summary> /// A Function/Proto/Chunk /// </summary> public class Chunk { /// <summary> /// The Chunk's name /// </summary> public string Name = ""; /// <summary> /// The first line /// </summary> public uint FirstLine = 1; /// <summary> /// The last line /// </summary> public ulong LastLine = 1; /// <summary> /// The number of upvalues in the chunk /// </summary> public int UpvalueCount = 0; /// <summary> /// The number of arguments this function/chunk recieves /// </summary> public int ArgumentCount = 0; /// <summary> /// The vararg flag of the chunk /// </summary> public int Vararg = 0; /// <summary> /// The Maximum stack size for this chunk /// </summary> public uint MaxStackSize = 250; /// <summary> /// The instructions in this chunk /// </summary> public List<Instruction> Instructions = new List<Instruction>(); /// <summary> /// The constants in this chunk /// </summary> public List<Constant> Constants = new List<Constant>(); /// <summary> /// The functions/protos in the chunk /// </summary> public List<Chunk> Protos = new List<Chunk>(); /// <summary> /// The locals in the chunk /// </summary> public List<Local> Locals = new List<Local>(); /// <summary> /// The upvalues in the chunk /// </summary> public List<Upvalue> Upvalues = new List<Upvalue>(); /// <summary> /// Creates a new empty chunk /// </summary> public Chunk() { } /// <summary> /// Creates a chunk from a Lua proto /// </summary> /// <param name="p"></param> public Chunk(Lua.Proto p) { Name = p.source.str.ToString(); MaxStackSize = p.maxstacksize; Vararg = p.is_vararg; ArgumentCount = p.numparams; UpvalueCount = p.nups; LastLine = (ulong)p.lastlinedefined; FirstLine = (uint)p.linedefined; foreach (uint instr in p.code) Instructions.Add(Instruction.From(instr)); foreach (Lua.lua_TValue k in p.k) { if (k.tt == Lua.LUA_TNIL) Constants.Add(new Constant(ConstantType.Nil, null)); else if (k.tt == Lua.LUA_TBOOLEAN) Constants.Add(new Constant(ConstantType.Bool, (int)k.value.p != 0)); else if (k.tt == Lua.LUA_TNUMBER) Constants.Add(new Constant(ConstantType.Number, k.value.n)); else if (k.tt == Lua.LUA_TSTRING) Constants.Add(new Constant(ConstantType.String, k.value.p.ToString())); } if (p.protos != null) foreach (Lua.Proto p2 in p.protos) Protos.Add(new Chunk(p2)); foreach (Lua.LocVar l in p.locvars) Locals.Add(new Local(l.varname.str.ToString(), l.startpc, l.endpc)); foreach (Lua.TString upval in p.upvalues) Upvalues.Add(new Upvalue(upval.str.ToString())); for (int i = 0; i < p.lineinfo.Length; i++) Instructions[i].LineNumber = p.lineinfo[i]; } public string Compile(LuaFile file) { Func<double, string> DumpNumber = PlatformConfig.GetNumberTypeConvertTo(file); Func<int, string> DumpInt = new Func<int, string>(delegate(int num) { string v = ""; for (int i = 0; i < file.IntegerSize; i++) { v += (char)(num % 256); num = (int)Math.Floor((double)num / 256); } return v; }); Func<string, string> DumpString = new Func<string, string>(delegate(string s) { int len = file.SizeT; //if (s == null || s.Length == 0) // return "\0".Repeat(len); //else //{ string l = DumpInt(s.Length + 1); return l + s + "\0"; //} }); string c = ""; c += DumpString(Name); c += DumpInt((int)FirstLine); c += DumpInt((int)LastLine); c += (char)UpvalueCount; c += (char)ArgumentCount; c += (char)Vararg; c += (char)MaxStackSize; // Instructions c += DumpInt(Instructions.Count); foreach (Instruction i in Instructions) c += DumpBinary.Opcode(i); // Constants c += DumpInt(Constants.Count); foreach (Constant cnst in Constants) { if (cnst.Type == ConstantType.Nil) c += (char)0; else if (cnst.Type == ConstantType.Bool) { c += (char)1; c += (char)((bool)cnst.Value ? 1 : 0); } else if (cnst.Type == ConstantType.Number) { c += (char)3; c += DumpNumber((double)cnst.Value); } else if (cnst.Type == ConstantType.String) { c += (char)4; c += DumpString((string)cnst.Value); } else throw new Exception("Invalid constant type: " + cnst.Type.ToString()); } // Protos c += DumpInt(Protos.Count); foreach (Chunk ch in Protos) c += ch.Compile(file); // Line Numbers int ln = 0; for (int i = 0; i < Instructions.Count; i++) if (Instructions[i].LineNumber != 0) ln = i; c += DumpInt(ln); for (int i = 0; i < ln; i++) c += DumpInt(Instructions[i].LineNumber); //c += DumpInt(Instructions.Count); //foreach (Instruction i in Instructions) // c += DumpInt(i.LineNumber); // Locals c += DumpInt(Locals.Count); foreach (Local l in Locals) { c += DumpString(l.Name); c += DumpInt(l.StartPC); c += DumpInt(l.EndPC); } // Upvalues c += DumpInt(Upvalues.Count); foreach (Upvalue v in Upvalues) c += DumpString(v.Name); return c; } public void StripDebugInfo() { Name = ""; FirstLine = 1; LastLine = 1; foreach (Instruction i in Instructions) i.LineNumber = 0; Locals.Clear(); foreach (Chunk p in Protos) p.StripDebugInfo(); Upvalues.Clear(); } public void Verify() { Verifier.VerifyChunk(this); foreach (Chunk c in Protos) c.Verify(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; namespace System.Data.Common { [ListBindable(false)] public sealed class DataTableMappingCollection : MarshalByRefObject, ITableMappingCollection { private List<DataTableMapping> _items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator public DataTableMappingCollection() { } // explicit ICollection implementation bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; // explicit IList implementation bool IList.IsReadOnly => false; bool IList.IsFixedSize => false; object IList.this[int index] { get { return this[index]; } set { ValidateType(value); this[index] = (DataTableMapping)value; } } object ITableMappingCollection.this[string index] { get { return this[index]; } set { ValidateType(value); this[index] = (DataTableMapping)value; } } ITableMapping ITableMappingCollection.Add(string sourceTableName, string dataSetTableName) => Add(sourceTableName, dataSetTableName); ITableMapping ITableMappingCollection.GetByDataSetTable(string dataSetTableName) => GetByDataSetTable(dataSetTableName); [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Count => (null != _items) ? _items.Count : 0; private Type ItemType => typeof(DataTableMapping); [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTableMapping this[int index] { get { RangeCheck(index); return _items[index]; } set { RangeCheck(index); Replace(index, value); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTableMapping this[string sourceTable] { get { int index = RangeCheck(sourceTable); return _items[index]; } set { int index = RangeCheck(sourceTable); Replace(index, value); } } public int Add(object value) { ValidateType(value); Add((DataTableMapping)value); return Count - 1; } private DataTableMapping Add(DataTableMapping value) { AddWithoutEvents(value); return value; } public void AddRange(DataTableMapping[] values) => AddEnumerableRange(values, false); public void AddRange(System.Array values) => AddEnumerableRange(values, false); private void AddEnumerableRange(IEnumerable values, bool doClone) { if (null == values) { throw ADP.ArgumentNull(nameof(values)); } foreach (object value in values) { ValidateType(value); } if (doClone) { foreach (ICloneable value in values) { AddWithoutEvents(value.Clone() as DataTableMapping); } } else { foreach (DataTableMapping value in values) { AddWithoutEvents(value); } } } public DataTableMapping Add(string sourceTable, string dataSetTable) => Add(new DataTableMapping(sourceTable, dataSetTable)); private void AddWithoutEvents(DataTableMapping value) { Validate(-1, value); value.Parent = this; ArrayList().Add(value); } // implemented as a method, not as a property because the VS7 debugger // object browser calls properties to display their value, and we want this delayed private List<DataTableMapping> ArrayList() => _items ?? (_items = new List<DataTableMapping>()); public void Clear() { if (0 < Count) { ClearWithoutEvents(); } } private void ClearWithoutEvents() { if (null != _items) { foreach (DataTableMapping item in _items) { item.Parent = null; } _items.Clear(); } } public bool Contains(string value) => (-1 != IndexOf(value)); public bool Contains(object value) => (-1 != IndexOf(value)); public void CopyTo(Array array, int index) => ((ICollection)ArrayList()).CopyTo(array, index); public void CopyTo(DataTableMapping[] array, int index) => ArrayList().CopyTo(array, index); public DataTableMapping GetByDataSetTable(string dataSetTable) { int index = IndexOfDataSetTable(dataSetTable); if (0 > index) { throw ADP.TablesDataSetTable(dataSetTable); } return _items[index]; } public IEnumerator GetEnumerator() => ArrayList().GetEnumerator(); public int IndexOf(object value) { if (null != value) { ValidateType(value); for (int i = 0; i < Count; ++i) { if (_items[i] == value) { return i; } } } return -1; } public int IndexOf(string sourceTable) { if (!string.IsNullOrEmpty(sourceTable)) { for (int i = 0; i < Count; ++i) { string value = _items[i].SourceTable; if ((null != value) && (0 == ADP.SrcCompare(sourceTable, value))) { return i; } } } return -1; } public int IndexOfDataSetTable(string dataSetTable) { if (!string.IsNullOrEmpty(dataSetTable)) { for (int i = 0; i < Count; ++i) { string value = _items[i].DataSetTable; if ((null != value) && (0 == ADP.DstCompare(dataSetTable, value))) { return i; } } } return -1; } public void Insert(int index, object value) { ValidateType(value); Insert(index, (DataTableMapping)value); } public void Insert(int index, DataTableMapping value) { if (null == value) { throw ADP.TablesAddNullAttempt(nameof(value)); } Validate(-1, value); value.Parent = this; ArrayList().Insert(index, value); } private void RangeCheck(int index) { if ((index < 0) || (Count <= index)) { throw ADP.TablesIndexInt32(index, this); } } private int RangeCheck(string sourceTable) { int index = IndexOf(sourceTable); if (index < 0) { throw ADP.TablesSourceIndex(sourceTable); } return index; } public void RemoveAt(int index) { RangeCheck(index); RemoveIndex(index); } public void RemoveAt(string sourceTable) { int index = RangeCheck(sourceTable); RemoveIndex(index); } private void RemoveIndex(int index) { Debug.Assert((null != _items) && (0 <= index) && (index < Count), "RemoveIndex, invalid"); _items[index].Parent = null; _items.RemoveAt(index); } public void Remove(object value) { ValidateType(value); Remove((DataTableMapping)value); } public void Remove(DataTableMapping value) { if (null == value) { throw ADP.TablesAddNullAttempt(nameof(value)); } int index = IndexOf(value); if (-1 != index) { RemoveIndex(index); } else { throw ADP.CollectionRemoveInvalidObject(ItemType, this); } } private void Replace(int index, DataTableMapping newValue) { Validate(index, newValue); _items[index].Parent = null; newValue.Parent = this; _items[index] = newValue; } private void ValidateType(object value) { if (null == value) { throw ADP.TablesAddNullAttempt(nameof(value)); } else if (!ItemType.IsInstanceOfType(value)) { throw ADP.NotADataTableMapping(value); } } private void Validate(int index, DataTableMapping value) { if (null == value) { throw ADP.TablesAddNullAttempt(nameof(value)); } if (null != value.Parent) { if (this != value.Parent) { throw ADP.TablesIsNotParent(this); } else if (index != IndexOf(value)) { throw ADP.TablesIsParent(this); } } string name = value.SourceTable; if (string.IsNullOrEmpty(name)) { index = 1; do { name = ADP.SourceTable + index.ToString(System.Globalization.CultureInfo.InvariantCulture); index++; } while (-1 != IndexOf(name)); value.SourceTable = name; } else { ValidateSourceTable(index, name); } } internal void ValidateSourceTable(int index, string value) { int pindex = IndexOf(value); if ((-1 != pindex) && (index != pindex)) { // must be non-null and unique throw ADP.TablesUniqueSourceTable(value); } } [EditorBrowsable(EditorBrowsableState.Advanced)] public static DataTableMapping GetTableMappingBySchemaAction(DataTableMappingCollection tableMappings, string sourceTable, string dataSetTable, MissingMappingAction mappingAction) { if (null != tableMappings) { int index = tableMappings.IndexOf(sourceTable); if (-1 != index) { return tableMappings._items[index]; } } if (string.IsNullOrEmpty(sourceTable)) { throw ADP.InvalidSourceTable(nameof(sourceTable)); } switch (mappingAction) { case MissingMappingAction.Passthrough: return new DataTableMapping(sourceTable, dataSetTable); case MissingMappingAction.Ignore: return null; case MissingMappingAction.Error: throw ADP.MissingTableMapping(sourceTable); default: throw ADP.InvalidMissingMappingAction(mappingAction); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The GroupCollection lists the captured Capture numbers // contained in a compiled Regex. using System.Collections; using System.Collections.Generic; namespace System.Text.RegularExpressions { /// <summary> /// Represents a sequence of capture substrings. The object is used /// to return the set of captures done by a single capturing group. /// </summary> public class GroupCollection : ICollection { internal Match _match; internal Dictionary<Int32, Int32> _captureMap; // cache of Group objects fed to the user internal Group[] _groups; /* * Nonpublic constructor */ internal GroupCollection(Match match, Dictionary<Int32, Int32> caps) { _match = match; _captureMap = caps; } /// <summary> /// The object on which to synchronize /// </summary> Object ICollection.SyncRoot { get { return _match; } } bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Returns the number of groups. /// </summary> public int Count { get { return _match._matchcount.Length; } } public Group this[int groupnum] { get { return GetGroup(groupnum); } } public Group this[String groupname] { get { if (_match._regex == null) return Group._emptygroup; return GetGroup(_match._regex.GroupNumberFromName(groupname)); } } internal Group GetGroup(int groupnum) { if (_captureMap != null) { Object o; o = _captureMap[groupnum]; if (o == null) return Group._emptygroup; //throw new ArgumentOutOfRangeException("groupnum"); return GetGroupImpl((int)o); } else { //if (groupnum >= _match._regex.CapSize || groupnum < 0) // throw new ArgumentOutOfRangeException("groupnum"); if (groupnum >= _match._matchcount.Length || groupnum < 0) return Group._emptygroup; return GetGroupImpl(groupnum); } } /* * Caches the group objects */ internal Group GetGroupImpl(int groupnum) { if (groupnum == 0) return _match; // Construct all the Group objects the first time GetGroup is called if (_groups == null) { _groups = new Group[_match._matchcount.Length - 1]; for (int i = 0; i < _groups.Length; i++) { _groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1]); } } return _groups[groupnum - 1]; } /// <summary> /// Copies all the elements of the collection to the given array /// beginning at the given index. /// </summary> void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); for (int i = arrayIndex, j = 0; j < Count; i++, j++) { array.SetValue(this[j], i); } } /// <summary> /// Provides an enumerator in the same order as Item[]. /// </summary> public IEnumerator GetEnumerator() { return new GroupEnumerator(this); } } /* * This non-public enumerator lists all the captures * Should it be public? */ internal class GroupEnumerator : IEnumerator { internal GroupCollection _rgc; internal int _curindex; /* * Nonpublic constructor */ internal GroupEnumerator(GroupCollection rgc) { _curindex = -1; _rgc = rgc; } /* * As required by IEnumerator */ public bool MoveNext() { int size = _rgc.Count; if (_curindex >= size) return false; _curindex++; return (_curindex < size); } /* * As required by IEnumerator */ public Object Current { get { return Capture; } } /* * Returns the current capture */ public Capture Capture { get { if (_curindex < 0 || _curindex >= _rgc.Count) throw new InvalidOperationException(SR.EnumNotStarted); return _rgc[_curindex]; } } /* * Reset to before the first item */ public void Reset() { _curindex = -1; } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; namespace CyPhyMasterInterpreterChecker { public static class Extensions { public static string ToSentenceCase(this string str) { return System.Text.RegularExpressions.Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1])); } public static string PadToCenter(this string str, int numChars) { return string.Format("{0,-" + numChars.ToString() + "}", String.Format("{0," + ((numChars + str.Length) / 2).ToString() + "}", str)); } public static string PadToLeft(this string str, int numChars) { return string.Format("{0,-" + numChars.ToString() + "}", str); } public static string PadToRight(this string str, int numChars) { return string.Format("{0," + numChars.ToString() + "}", str); } } /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhyMasterInterpreterCheckerInterpreter : IMgaComponentEx, IGMEVersionInfo { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... } #region IMgaComponentEx Members MgaGateway MgaGateway { get; set; } GMEConsole GMEConsole { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE; //bool runNewImplementationOnly = true; //runNewImplementationOnly = false; //if (runNewImplementationOnly) //{ // this.NewMasterInterpreterImplementationFull(currentobj); // return; //} List<IMgaFCO> objectsToCheck = new List<IMgaFCO>(); List<IMgaFCO> objectsToGetConfigurations = new List<IMgaFCO>(); MgaGateway.PerformInTransaction(() => { if (currentobj == null) { var allObjects = project .RootFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker"))); objectsToGetConfigurations.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations"))); } else { objectsToCheck.Add(currentobj); //objectsToGetConfigurations.Add(currentobj); } objectsToCheck.Sort((x, y) => { return x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath); }); }); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; StringBuilder sbAssumptions = new StringBuilder(); sbAssumptions.Append("Implemented".PadToCenter(11)); sbAssumptions.Append("Valid".PadToCenter(11)); sbAssumptions.Append("Context".PadToCenter(30)); sbAssumptions.Append("Assumption"); sbAssumptions.AppendLine(); foreach (var subject in objectsToCheck) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); IEnumerable<CyPhyMasterInterpreter.Rules.ContextCheckerResult> contextCheckerResults = null; // check context var checkerSuccess = masterInterpreter.TryCheckContext(subject as MgaModel, out contextCheckerResults); List<CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success); }); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; sbAssumptions.AppendFormat("{0}{1}{2}{3}", (successExpected == checkerSuccess).ToString().PadToCenter(11), successExpected.ToString().PadToCenter(11), subject.Meta.Name.PadToCenter(30), subject.Name.ToSentenceCase()); sbAssumptions.AppendLine(); if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); if (currentobj != null) { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } } } else { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; GMEConsole.Error.WriteLine("========= FAILED =========="); GMEConsole.Error.WriteLine("= {0}", subject.Name); GMEConsole.Error.WriteLine("= {0}", subject.AbsPath); GMEConsole.Error.WriteLine("==========================="); } }); if (currentobj != null) { CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; MgaGateway.PerformInTransaction(() => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }); GMEConsole.Info.WriteLine("AnalysisProcessor type: {0}", analysisModelProcessor.GetType().Name); GMEConsole.Info.WriteLine("Interpreters: {0}", string.Join(", ", analysisModelProcessor.Interpreters)); GMEConsole.Info.WriteLine("InterpretersToConfigure: {0}", string.Join(", ", analysisModelProcessor.InterpretersToConfiguration)); MgaFCO configuration = null; configuration = masterInterpreter.GetConfigurations(subject as MgaModel).Cast<MgaFCO>().FirstOrDefault(); var results = masterInterpreter.RunInTransaction(subject as MgaModel, configuration, keepTempModels: true); MgaGateway.PerformInTransaction(() => { foreach (var result in results) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i>{0}</i> {1} ", result.Context.Name, result.Configuration.Name); sb.Append(result.Message); tw.WriteLine(sb); } }); } } File.WriteAllText("master_interpreter_assumptions.txt", sbAssumptions.ToString()); foreach (var subject in objectsToGetConfigurations) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); // we are not checking the models again, these test models must be valid enough to get configurations from them var configurations = masterInterpreter.GetConfigurations(subject as MgaModel); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { GMEConsole.Info.WriteLine("{0} has {1} configurations.", subject.Name, configurations.Count); //GMEConsole.Info.WriteLine("- {0}", string.Join(", ", configurations.Cast<MgaFCO>().Select(x => x.Name))); }); //CyPhyMasterInterpreter.MasterInterpreterResult[] masterInterpreterResults = null; //using (var progressDialog = new CyPhyMasterInterpreter.ProgressDialog()) //{ // masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler; // masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler; // progressDialog.ShowWithDisabledMainWindow(); // masterInterpreterResults = masterInterpreter.RunInTransaction(subject as IMgaModel, configurations); //} } GMEConsole.Info.WriteLine("ContextChecks: {0}", numContexts); GMEConsole.Info.WriteLine("Successful : {0}", numSuccess); GMEConsole.Info.WriteLine("Failures : {0}", numFailures); if (numContexts == numSuccess) { GMEConsole.Info.WriteLine("ALL GREEN :-)"); } else { GMEConsole.Error.WriteLine("You need to work more on the code..."); } GMEConsole.Info.WriteLine( "Duration: {0}.", sw.Elapsed.ToString("c")); } finally { System.Windows.Forms.Application.DoEvents(); if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } private void NewMasterInterpreterImplementationFull(MgaFCO currentobj) { this.GMEConsole.Clear(); System.Windows.Forms.Application.DoEvents(); this.GMEConsole.Info.WriteLine("Running Master Interpreter 2.0"); if (currentobj == null) { GMEConsole.Error.WriteLine("Context is invalid. This component can be executed only if a valid context is open in the main editor e.g. Test Bench."); return; } var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); masterInterpreter.IsInteractive = this.InteractiveMode; IEnumerable<CyPhyMasterInterpreter.Rules.ContextCheckerResult> contextCheckerResults = null; // check context var checkerSuccess = masterInterpreter.TryCheckContext(currentobj as MgaModel, out contextCheckerResults); List<CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success); }); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } }); if (sortedResults.Any(x => x.Success == false)) { GMEConsole.Error.WriteLine("Context is invalid see messeges above. Please fix the problems."); return; } // context is valid // show GUI for the user CyPhyMasterInterpreter.ConfigurationSelection selection = null; try { selection = masterInterpreter.ShowConfigurationSelectionForm(currentobj as MgaModel); } catch (CyPhyMasterInterpreter.ExecutionCanceledByUserException ex) { GMEConsole.Warning.WriteLine("Operation was canceled by user. {0}", ex.Message); return; } CyPhyMasterInterpreter.MasterInterpreterResult[] miResults = null; // Get a progress dialog using (var progressDialog = new CyPhyMasterInterpreter.ProgressDialog()) { masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler; masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler; if (masterInterpreter.IsInteractive) { progressDialog.ShowWithDisabledMainWindow(); } try { miResults = masterInterpreter.RunInTransaction(selection); } catch (CyPhyMasterInterpreter.AnalysisModelInterpreterConfigurationFailedException ex) { GMEConsole.Warning.WriteLine("Operation was canceled by user. {0}", ex.Message); } catch (CyPhyMasterInterpreter.ExecutionCanceledByUserException ex) { GMEConsole.Warning.WriteLine("Operation was canceled by user. {0}", ex.Message); } } if (selection.OpenDashboard) { masterInterpreter.OpenDashboardWithChrome(); } GMEConsole.Info.WriteLine(" === Summary === "); MgaGateway.PerformInTransaction(() => { // print failure/success statistics // user master interpreter's result set in case user canceled the execution foreach (var result in masterInterpreter.Results) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i>{0}</i> {1} ", result.Context.Name, result.Configuration.Name); sb.Append(result.Message); tw.WriteLine(sb); } }); this.GMEConsole.Info.WriteLine("Done Master Interpreter 2.0"); } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion } }
using J2N.Text; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace YAF.Lucene.Net.Codecs.Lucene40 { /* * 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 ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil; using AtomicReader = YAF.Lucene.Net.Index.AtomicReader; using IBits = YAF.Lucene.Net.Util.IBits; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using DataInput = YAF.Lucene.Net.Store.DataInput; using Directory = YAF.Lucene.Net.Store.Directory; using FieldInfo = YAF.Lucene.Net.Index.FieldInfo; using FieldInfos = YAF.Lucene.Net.Index.FieldInfos; using Fields = YAF.Lucene.Net.Index.Fields; using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames; using IndexOutput = YAF.Lucene.Net.Store.IndexOutput; using IOContext = YAF.Lucene.Net.Store.IOContext; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using MergeState = YAF.Lucene.Net.Index.MergeState; using SegmentReader = YAF.Lucene.Net.Index.SegmentReader; using StringHelper = YAF.Lucene.Net.Util.StringHelper; // TODO: make a new 4.0 TV format that encodes better // - use startOffset (not endOffset) as base for delta on // next startOffset because today for syns or ngrams or // WDF or shingles etc. we are encoding negative vints // (= slow, 5 bytes per) // - if doc has no term vectors, write 0 into the tvx // file; saves a seek to tvd only to read a 0 vint (and // saves a byte in tvd) /// <summary> /// Lucene 4.0 Term Vectors writer. /// <para/> /// It writes .tvd, .tvf, and .tvx files. /// </summary> /// <seealso cref="Lucene40TermVectorsFormat"/> public sealed class Lucene40TermVectorsWriter : TermVectorsWriter { private readonly Directory directory; private readonly string segment; private IndexOutput tvx = null, tvd = null, tvf = null; /// <summary> /// Sole constructor. </summary> public Lucene40TermVectorsWriter(Directory directory, string segment, IOContext context) { this.directory = directory; this.segment = segment; bool success = false; try { // Open files for TermVector storage tvx = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_INDEX_EXTENSION), context); CodecUtil.WriteHeader(tvx, Lucene40TermVectorsReader.CODEC_NAME_INDEX, Lucene40TermVectorsReader.VERSION_CURRENT); tvd = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_DOCUMENTS_EXTENSION), context); CodecUtil.WriteHeader(tvd, Lucene40TermVectorsReader.CODEC_NAME_DOCS, Lucene40TermVectorsReader.VERSION_CURRENT); tvf = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_FIELDS_EXTENSION), context); CodecUtil.WriteHeader(tvf, Lucene40TermVectorsReader.CODEC_NAME_FIELDS, Lucene40TermVectorsReader.VERSION_CURRENT); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_INDEX == tvx.GetFilePointer()); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_DOCS == tvd.GetFilePointer()); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_FIELDS == tvf.GetFilePointer()); success = true; } finally { if (!success) { Abort(); } } } public override void StartDocument(int numVectorFields) { lastFieldName = null; this.numVectorFields = numVectorFields; tvx.WriteInt64(tvd.GetFilePointer()); tvx.WriteInt64(tvf.GetFilePointer()); tvd.WriteVInt32(numVectorFields); fieldCount = 0; fps = ArrayUtil.Grow(fps, numVectorFields); } private long[] fps = new long[10]; // pointers to the tvf before writing each field private int fieldCount = 0; // number of fields we have written so far for this document private int numVectorFields = 0; // total number of fields we will write for this document private string lastFieldName; public override void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads) { Debug.Assert(lastFieldName == null || info.Name.CompareToOrdinal(lastFieldName) > 0, "fieldName=" + info.Name + " lastFieldName=" + lastFieldName); lastFieldName = info.Name; this.positions = positions; this.offsets = offsets; this.payloads = payloads; lastTerm.Length = 0; lastPayloadLength = -1; // force first payload to write its length fps[fieldCount++] = tvf.GetFilePointer(); tvd.WriteVInt32(info.Number); tvf.WriteVInt32(numTerms); sbyte bits = 0x0; if (positions) { bits |= Lucene40TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR; } if (offsets) { bits |= Lucene40TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR; } if (payloads) { bits |= Lucene40TermVectorsReader.STORE_PAYLOAD_WITH_TERMVECTOR; } tvf.WriteByte((byte)bits); } [MethodImpl(MethodImplOptions.NoInlining)] public override void FinishDocument() { Debug.Assert(fieldCount == numVectorFields); for (int i = 1; i < fieldCount; i++) { tvd.WriteVInt64(fps[i] - fps[i - 1]); } } private readonly BytesRef lastTerm = new BytesRef(10); // NOTE: we override addProx, so we don't need to buffer when indexing. // we also don't buffer during bulk merges. private int[] offsetStartBuffer = new int[10]; private int[] offsetEndBuffer = new int[10]; private BytesRef payloadData = new BytesRef(10); private int bufferedIndex = 0; private int bufferedFreq = 0; private bool positions = false; private bool offsets = false; private bool payloads = false; public override void StartTerm(BytesRef term, int freq) { int prefix = StringHelper.BytesDifference(lastTerm, term); int suffix = term.Length - prefix; tvf.WriteVInt32(prefix); tvf.WriteVInt32(suffix); tvf.WriteBytes(term.Bytes, term.Offset + prefix, suffix); tvf.WriteVInt32(freq); lastTerm.CopyBytes(term); lastPosition = lastOffset = 0; if (offsets && positions) { // we might need to buffer if its a non-bulk merge offsetStartBuffer = ArrayUtil.Grow(offsetStartBuffer, freq); offsetEndBuffer = ArrayUtil.Grow(offsetEndBuffer, freq); } bufferedIndex = 0; bufferedFreq = freq; payloadData.Length = 0; } internal int lastPosition = 0; internal int lastOffset = 0; internal int lastPayloadLength = -1; // force first payload to write its length internal BytesRef scratch = new BytesRef(); // used only by this optimized flush below public override void AddProx(int numProx, DataInput positions, DataInput offsets) { if (payloads) { // TODO, maybe overkill and just call super.addProx() in this case? // we do avoid buffering the offsets in RAM though. for (int i = 0; i < numProx; i++) { int code = positions.ReadVInt32(); if ((code & 1) == 1) { int length = positions.ReadVInt32(); scratch.Grow(length); scratch.Length = length; positions.ReadBytes(scratch.Bytes, scratch.Offset, scratch.Length); WritePosition((int)((uint)code >> 1), scratch); } else { WritePosition((int)((uint)code >> 1), null); } } tvf.WriteBytes(payloadData.Bytes, payloadData.Offset, payloadData.Length); } else if (positions != null) { // pure positions, no payloads for (int i = 0; i < numProx; i++) { tvf.WriteVInt32((int)((uint)positions.ReadVInt32() >> 1)); } } if (offsets != null) { for (int i = 0; i < numProx; i++) { tvf.WriteVInt32(offsets.ReadVInt32()); tvf.WriteVInt32(offsets.ReadVInt32()); } } } public override void AddPosition(int position, int startOffset, int endOffset, BytesRef payload) { if (positions && (offsets || payloads)) { // write position delta WritePosition(position - lastPosition, payload); lastPosition = position; // buffer offsets if (offsets) { offsetStartBuffer[bufferedIndex] = startOffset; offsetEndBuffer[bufferedIndex] = endOffset; } bufferedIndex++; } else if (positions) { // write position delta WritePosition(position - lastPosition, payload); lastPosition = position; } else if (offsets) { // write offset deltas tvf.WriteVInt32(startOffset - lastOffset); tvf.WriteVInt32(endOffset - startOffset); lastOffset = endOffset; } } public override void FinishTerm() { if (bufferedIndex > 0) { // dump buffer Debug.Assert(positions && (offsets || payloads)); Debug.Assert(bufferedIndex == bufferedFreq); if (payloads) { tvf.WriteBytes(payloadData.Bytes, payloadData.Offset, payloadData.Length); } if (offsets) { for (int i = 0; i < bufferedIndex; i++) { tvf.WriteVInt32(offsetStartBuffer[i] - lastOffset); tvf.WriteVInt32(offsetEndBuffer[i] - offsetStartBuffer[i]); lastOffset = offsetEndBuffer[i]; } } } } private void WritePosition(int delta, BytesRef payload) { if (payloads) { int payloadLength = payload == null ? 0 : payload.Length; if (payloadLength != lastPayloadLength) { lastPayloadLength = payloadLength; tvf.WriteVInt32((delta << 1) | 1); tvf.WriteVInt32(payloadLength); } else { tvf.WriteVInt32(delta << 1); } if (payloadLength > 0) { if (payloadLength + payloadData.Length < 0) { // we overflowed the payload buffer, just throw UOE // having > System.Int32.MaxValue bytes of payload for a single term in a single doc is nuts. throw new System.NotSupportedException("A term cannot have more than System.Int32.MaxValue bytes of payload data in a single document"); } payloadData.Append(payload); } } else { tvf.WriteVInt32(delta); } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { try { Dispose(); } #pragma warning disable 168 catch (Exception ignored) #pragma warning restore 168 { } IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_INDEX_EXTENSION), IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_DOCUMENTS_EXTENSION), IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_FIELDS_EXTENSION)); } /// <summary> /// Do a bulk copy of numDocs documents from reader to our /// streams. This is used to expedite merging, if the /// field numbers are congruent. /// </summary> private void AddRawDocuments(Lucene40TermVectorsReader reader, int[] tvdLengths, int[] tvfLengths, int numDocs) { long tvdPosition = tvd.GetFilePointer(); long tvfPosition = tvf.GetFilePointer(); long tvdStart = tvdPosition; long tvfStart = tvfPosition; for (int i = 0; i < numDocs; i++) { tvx.WriteInt64(tvdPosition); tvdPosition += tvdLengths[i]; tvx.WriteInt64(tvfPosition); tvfPosition += tvfLengths[i]; } tvd.CopyBytes(reader.TvdStream, tvdPosition - tvdStart); tvf.CopyBytes(reader.TvfStream, tvfPosition - tvfStart); Debug.Assert(tvd.GetFilePointer() == tvdPosition); Debug.Assert(tvf.GetFilePointer() == tvfPosition); } [MethodImpl(MethodImplOptions.NoInlining)] public override int Merge(MergeState mergeState) { // Used for bulk-reading raw bytes for term vectors int[] rawDocLengths = new int[MAX_RAW_MERGE_DOCS]; int[] rawDocLengths2 = new int[MAX_RAW_MERGE_DOCS]; int idx = 0; int numDocs = 0; for (int i = 0; i < mergeState.Readers.Count; i++) { AtomicReader reader = mergeState.Readers[i]; SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++]; Lucene40TermVectorsReader matchingVectorsReader = null; if (matchingSegmentReader != null) { TermVectorsReader vectorsReader = matchingSegmentReader.TermVectorsReader; if (vectorsReader != null && vectorsReader is Lucene40TermVectorsReader) { matchingVectorsReader = (Lucene40TermVectorsReader)vectorsReader; } } if (reader.LiveDocs != null) { numDocs += CopyVectorsWithDeletions(mergeState, matchingVectorsReader, reader, rawDocLengths, rawDocLengths2); } else { numDocs += CopyVectorsNoDeletions(mergeState, matchingVectorsReader, reader, rawDocLengths, rawDocLengths2); } } Finish(mergeState.FieldInfos, numDocs); return numDocs; } /// <summary> /// Maximum number of contiguous documents to bulk-copy /// when merging term vectors. /// </summary> private const int MAX_RAW_MERGE_DOCS = 4192; private int CopyVectorsWithDeletions(MergeState mergeState, Lucene40TermVectorsReader matchingVectorsReader, AtomicReader reader, int[] rawDocLengths, int[] rawDocLengths2) { int maxDoc = reader.MaxDoc; IBits liveDocs = reader.LiveDocs; int totalNumDocs = 0; if (matchingVectorsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" for (int docNum = 0; docNum < maxDoc; ) { if (!liveDocs.Get(docNum)) { // skip deleted docs ++docNum; continue; } // We can optimize this case (doing a bulk byte copy) since the field // numbers are identical int start = docNum, numDocs = 0; do { docNum++; numDocs++; if (docNum >= maxDoc) { break; } if (!liveDocs.Get(docNum)) { docNum++; break; } } while (numDocs < MAX_RAW_MERGE_DOCS); matchingVectorsReader.RawDocs(rawDocLengths, rawDocLengths2, start, numDocs); AddRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, numDocs); totalNumDocs += numDocs; mergeState.CheckAbort.Work(300 * numDocs); } } else { for (int docNum = 0; docNum < maxDoc; docNum++) { if (!liveDocs.Get(docNum)) { // skip deleted docs continue; } // NOTE: it's very important to first assign to vectors then pass it to // termVectorsWriter.addAllDocVectors; see LUCENE-1282 Fields vectors = reader.GetTermVectors(docNum); AddAllDocVectors(vectors, mergeState); totalNumDocs++; mergeState.CheckAbort.Work(300); } } return totalNumDocs; } private int CopyVectorsNoDeletions(MergeState mergeState, Lucene40TermVectorsReader matchingVectorsReader, AtomicReader reader, int[] rawDocLengths, int[] rawDocLengths2) { int maxDoc = reader.MaxDoc; if (matchingVectorsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" int docCount = 0; while (docCount < maxDoc) { int len = Math.Min(MAX_RAW_MERGE_DOCS, maxDoc - docCount); matchingVectorsReader.RawDocs(rawDocLengths, rawDocLengths2, docCount, len); AddRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, len); docCount += len; mergeState.CheckAbort.Work(300 * len); } } else { for (int docNum = 0; docNum < maxDoc; docNum++) { // NOTE: it's very important to first assign to vectors then pass it to // termVectorsWriter.addAllDocVectors; see LUCENE-1282 Fields vectors = reader.GetTermVectors(docNum); AddAllDocVectors(vectors, mergeState); mergeState.CheckAbort.Work(300); } } return maxDoc; } public override void Finish(FieldInfos fis, int numDocs) { if (Lucene40TermVectorsReader.HEADER_LENGTH_INDEX + ((long)numDocs) * 16 != tvx.GetFilePointer()) // this is most likely a bug in Sun JRE 1.6.0_04/_05; // we detect that the bug has struck, here, and // throw an exception to prevent the corruption from // entering the index. See LUCENE-1282 for // details. { throw new Exception("tvx size mismatch: mergedDocs is " + numDocs + " but tvx size is " + tvx.GetFilePointer() + " file=" + tvx.ToString() + "; now aborting this merge to prevent index corruption"); } } /// <summary> /// Close all streams. </summary> protected override void Dispose(bool disposing) { if (disposing) { // make an effort to close all streams we can but remember and re-throw // the first exception encountered in this process IOUtils.Dispose(tvx, tvd, tvf); tvx = tvd = tvf = null; } } public override IComparer<BytesRef> Comparer { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System.Net; using System.Web; using ECQRS.Commons.Commands; using ECQRS.Commons.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using UserManager.Core.Applications.Commands; using UserManager.Core.Applications.ReadModel; using UserManager.Model.Applications; using UserManager.Core.Users.ReadModel; using UserManager.Core.Users.Commands; namespace UserManager.Api { [Authorize] public class ApplicationRolesController : ApiController { private readonly IRepository<ApplicationRoleItem> _roles; private readonly IRepository<ApplicationRolePermissionItem> _rolesPermissions; private readonly IRepository<ApplicationPermissionItem> _permissions; private readonly IRepository<UserListItem> _users; private readonly ICommandSender _bus; public ApplicationRolesController( IRepository<ApplicationRoleItem> list, IRepository<ApplicationRolePermissionItem> rolesPermissions, IRepository<ApplicationPermissionItem> permissions, IRepository<UserListItem> users, ICommandSender bus) { _roles = list; _bus = bus; _rolesPermissions = rolesPermissions; _permissions = permissions; _users = users; } // GET: api/Applications [Route("api/ApplicationRoles/list/{applicationId}")] public IEnumerable<ApplicationRoleItem> GetList(Guid? applicationId, string range = null, string filter = null) { if (applicationId == null) throw new HttpException(400, "Invalid application Id"); var parsedRange = AngularApiUtils.ParseRange(range); var parsedFilters = AngularApiUtils.ParseFilter(filter); var where = _roles.Where(a => a.ApplicationId == applicationId.Value && a.Deleted == false); if (parsedFilters.ContainsKey("Code")) where = where.Where(a => a.Code.Contains(parsedFilters["Code"].ToString())); if (parsedFilters.ContainsKey("Description")) where = where.Where(a => a.Description.Contains(parsedFilters["Description"].ToString())); return where .DoSkip(parsedRange.From).DoTake(parsedRange.Count); } // GET: api/Applications/5/1 public ApplicationRoleItem Get(Guid id) { var res = _roles.Get(id); if (res != null) return res; return null; } // POST: api/Applications public void Post([FromBody]ApplicationRoleCreateModel value) { _bus.SendSync(new ApplicationRoleCreate { Code = value.Code, Description = value.Description, ApplicationId = value.ApplicationId, RoleId = Guid.NewGuid() }); } // PUT: api/Applications public void Put([FromBody]ApplicationRoleModifyModel value) { _bus.SendSync(new ApplicationRoleModify { Code = value.Code, Description = value.Description, ApplicationId = value.ApplicationId, RoleId = value.Id }); } // DELETE: api/Applications/5 public void Delete(Guid id) { var item = _roles.Get(id); _bus.SendSync(new ApplicationRoleDelete { ApplicationId = item.ApplicationId, RoleId = item.Id }); } [Route("api/ApplicationRoles/permissions/{applicationId}/{roleId}")] public IEnumerable<ApplicationRolePermissionModel> GetList(Guid? applicationId, Guid? roleId, string range = null, string filter = null) { if (applicationId == null) throw new HttpException(400, "Invalid application Id"); if (roleId == null) throw new HttpException(400, "Invalid role Id"); var parsedRange = AngularApiUtils.ParseRange(range); var parsedFilters = AngularApiUtils.ParseFilter(filter); //Retrieve the permissions for the given application/role var associatedPermissions = _rolesPermissions.Where(p => p.RoleId == roleId.Value && p.ApplicationId == applicationId.Value && p.Deleted == false) .ToList(); //Retrieve all the permissions exposed by the application var wherePermissions = _permissions.Where(a => a.ApplicationId == applicationId.Value && a.Deleted == false); if (parsedFilters.ContainsKey("Code")) wherePermissions = wherePermissions.Where(a => a.Code.Contains(parsedFilters["Code"].ToString())); if (parsedFilters.ContainsKey("Description")) wherePermissions = wherePermissions.Where(a => a.Description.Contains(parsedFilters["Description"].ToString())); return wherePermissions .DoSkip(parsedRange.From).DoTake(parsedRange.Count) .Select(u => { var item = u.ToApplicationRolePermissionModel(roleId.Value); var matching = associatedPermissions.FirstOrDefault(a => a.PermissionId == item.PermissionId); item.Selected = matching != null; if (matching != null) { item.Id = matching.Id; } return item; }).ToList(); } [HttpPost] [Route("api/ApplicationRoles/permissions/{applicationId}/{roleId}")] public void AddApplicationRole(Guid? applicationId, Guid? roleId, ApplicationRolePermissionItem value) { if (applicationId == null) throw new HttpException(400, "Invalid application Id"); if (roleId == null) throw new HttpException(400, "Invalid role Id"); _bus.SendSync(new ApplicationRolePermissionAdd { ApplicationId = applicationId.Value, RoleId = roleId.Value, PermissionId = value.PermissionId, RolePermissionId = Guid.NewGuid() }); } [HttpDelete] [Route("api/ApplicationRoles/permissions/{applicationId}/{roleId}/{id}")] public void DeleteApplicationRole(Guid? applicationId, Guid? roleId, Guid? id) { if (applicationId == null) throw new HttpException(400, "Invalid application Id"); if (roleId == null) throw new HttpException(400, "Invalid role Id"); if (id == null) throw new HttpException(400, "Invalid application-role Id"); var item = _rolesPermissions.Get(id.Value); _bus.SendSync(new ApplicationRolePermissionDelete { ApplicationId = applicationId.Value, RoleId = item.RoleId, PermissionId = item.PermissionId, RolePermissionId = item.Id }); } //// GET: api/Users for application //[Route("api/ApplicationUsers/{applicationId}")] //public IEnumerable<UserListItem> GetUsersByApplication(Guid? applicationId, string range = null, string filter = null) //{ // if (applicationId == null) throw new HttpException(400, "Invalid application Id"); // var parsedRange = AngularApiUtils.ParseRange(range); // var parsedFilters = AngularApiUtils.ParseFilter(filter); // var appUsers = _userApplicationItems.Where(u => u.ApplicationId == applicationId.Value).ToList().Select(u => u.UserId).ToList(); // parsedFilters.Add("Id", appUsers); // var whereUsers = _users.Where(a => appUsers.Contains(a.Id)); // if (parsedFilters.ContainsKey("UserName")) whereUsers = whereUsers.Where(a => a.UserName.Contains(parsedFilters["UserName"].ToString())); // if (parsedFilters.ContainsKey("EMail")) whereUsers = whereUsers.Where(a => a.EMail.Contains(parsedFilters["EMail"].ToString())); // var result = whereUsers // .Skip(parsedRange.From).Take(parsedRange.Count) // .ToList(); // return result; //} } }
/* Copyright 2015 System Era Softworks 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.Reflection; using System.Collections.Generic; using System.Linq; // Lots of reflection utility functions public static class TypeUtil { public static object InvokeDefaultConstructor(this Type type) { return type.GetConstructor(new Type[] { }).Invoke(new object[] { }); } public static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } public static void BreakpointMe() { UnityEngine.Debug.Log("Breakpoint here"); } public static bool IsGenericSubclass(Type type, Type genericDefinition) { if (type.IsGenericTypeDefinition) return false; while (type != null) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericDefinition) return true; if (genericDefinition.IsInterface && type.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition)) return true; type = type.BaseType; } return false; } public static Type[] GetGenericSubclassArguments(Type type, Type genericDefinition) { if (type.IsGenericTypeDefinition) return new Type[] {}; while (type != null) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericDefinition) return type.GetGenericArguments(); if (genericDefinition.IsInterface) { var interfaceGenericType = type.GetInterfaces().FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition); if (interfaceGenericType != null) return interfaceGenericType.GetGenericArguments(); } type = type.BaseType; } return new Type[] {}; } public static Type GetGenericSubclass(Type type, Type genericDefinition) { return genericDefinition.MakeGenericType(GetGenericSubclassArguments(type, genericDefinition)); } public static object Default(Type t) { if (t.IsValueType) return Activator.CreateInstance(t); else if (t == typeof(string)) return ""; else if (t.IsAbstract || t.IsSubclassOf(typeof(UnityEngine.Object))) return null; else { var constructor = t.GetConstructor(new Type[] { }); if (constructor != null) return constructor.Invoke(new object[] { }); else return null; } } private class DefaultFunc<T> { private static T Invoke() { return Default<T>(); } public static Func<T> GetInvoke() { return Invoke; } } public static T Default<T>() { if (typeof(T).IsValueType || typeof(T).IsSubclassOf(typeof(UnityEngine.Object))) return default(T); else if (typeof(T) == typeof(string)) return (T)(object)""; else if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Func<>)) { Type defaultFuncType = typeof(DefaultFunc<>).MakeGenericType(new Type[] { typeof(T).GetGenericArguments()[0] }); return (T)defaultFuncType.GetMethod("GetInvoke").Invoke(null, new object[] {}); } else { var constructor = typeof(T).GetConstructor(new Type[] {}); if (constructor != null) return (T)constructor.Invoke(new object[] {}); else return default(T); } } public class ConstructOfTypeDefault { Type T; public ConstructOfTypeDefault(Type t) { T = t; } public object Invoke(object[] o) { return TypeUtil.Default(T); } } public static string CleanName(string typeName) { if (typeName == null) return ""; return SplitCamelCase(typeName, " "); } public static string TypeName(Type type, bool stripMenu = true, bool cleanName = true) { var typeNameAttrs = type.GetCustomAttributes(typeof(NameAttribute), true); if (typeNameAttrs.Length > 0) { string nameValue = (typeNameAttrs[0] as NameAttribute).Value; if (stripMenu) return nameValue.Split('/').Last(); else return nameValue; } else { if (type.IsGenericType) { if (TypeUtil.IsGenericSubclass(type, typeof(IRef<>))) return TypeName(type.GetGenericArguments()[0], stripMenu, cleanName); if (TypeUtil.IsGenericSubclass(type, typeof(INamed<>))) return TypeName(type.GetGenericArguments()[0], stripMenu, cleanName); return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => TypeName(x, true, false)).ToArray()) + ">"; } else if (cleanName) return CleanName(type.Name); else return type.Name; } } // Get readable field name public static string SplitCamelCase(string str, string delimiter) { string wildcard = "$1" + delimiter + "$2"; return System.Text.RegularExpressions.Regex.Replace( System.Text.RegularExpressions.Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", wildcard ), @"(\p{Ll})(\P{Ll})", wildcard ); } public static string ByteArrayToString(byte[] ba) { System.Text.StringBuilder hex = new System.Text.StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); } } // Useful enumerable extensions. public static class EnumerableExt { public static IEnumerable<T> Single<T>(T t) { return Enumerable.Repeat(t, 1); } public static IEnumerable<T> ConcatSingle<T>(this IEnumerable<T> e, T t) { return e.Concat(Single<T>(t)); } } public static class CloneExt { public static T Clone<T>(this T other) { return FullInspector.SerializationHelpers.Clone<T, FullInspector.ModifiedJsonNetSerializer>(other); } public static T CloneCached<T>(this T other) { return FullInspector.SerializationHelpersExt.CloneCached<T, FullInspector.ModifiedJsonNetSerializer>(other); } public static void Clone<T>(this T other, T target) { var serializer = FullInspector.Internal.fiSingletons.Get<FullInspector.ModifiedJsonNetSerializer>(); var serializationOperator = FullInspector.Internal.fiSingletons.Get<FullInspector.Internal.ListSerializationOperator>(); serializationOperator.SerializedObjects = new List<UnityEngine.Object>(); string serialized = serializer.Serialize(typeof(T), other, serializationOperator); serializer.Deserialize(target, serialized, serializationOperator); serializationOperator.SerializedObjects = null; } }
using System.Runtime.Intrinsics; using NUnit.Framework; using TerraFX.Numerics; using static TerraFX.Utilities.VectorUtilities; using SysMatrix4x4 = System.Numerics.Matrix4x4; namespace TerraFX.UnitTests.Numerics; /// <summary>Provides a set of tests covering the <see cref="Matrix4x4" /> struct.</summary> [TestFixture(TestOf = typeof(Matrix4x4))] public class Matrix4x4Tests { /// <summary>Provides validation of the <see cref="Matrix4x4.Zero" /> property.</summary> [Test] public static void ZeroTest() { Assert.That(() => Matrix4x4.Zero, Is.EqualTo(Matrix4x4.Create(Vector4.Zero, Vector4.Zero, Vector4.Zero, Vector4.Zero)) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.Identity" /> property.</summary> [Test] public static void IdentityTest() { Assert.That(() => Matrix4x4.Identity, Is.EqualTo(Matrix4x4.Create(UnitX, UnitY, UnitZ, UnitW)) ); } /// <summary>Provides validation of the <see cref="M:Matrix4x4.Create" /> methods.</summary> [Test] public static void CreateTest() { var value = Matrix4x4.Zero; Assert.That(() => value.X, Is.EqualTo(Vector4.Zero)); Assert.That(() => value.Y, Is.EqualTo(Vector4.Zero)); Assert.That(() => value.Z, Is.EqualTo(Vector4.Zero)); Assert.That(() => value.W, Is.EqualTo(Vector4.Zero)); value = Matrix4x4.Create( Vector128.Create(00.0f, 01.0f, 02.0f, 03.0f), Vector128.Create(04.0f, 05.0f, 06.0f, 07.0f), Vector128.Create(08.0f, 09.0f, 10.0f, 11.0f), Vector128.Create(12.0f, 13.0f, 14.0f, 15.0f) ); Assert.That(() => value.X, Is.EqualTo(Vector4.Create(00.0f, 01.0f, 02.0f, 03.0f))); Assert.That(() => value.Y, Is.EqualTo(Vector4.Create(04.0f, 05.0f, 06.0f, 07.0f))); Assert.That(() => value.Z, Is.EqualTo(Vector4.Create(08.0f, 09.0f, 10.0f, 11.0f))); Assert.That(() => value.W, Is.EqualTo(Vector4.Create(12.0f, 13.0f, 14.0f, 15.0f))); value = Matrix4x4.Create(new SysMatrix4x4( 16.0f, 17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f, 24.0f, 25.0f, 26.0f, 27.0f, 28.0f, 29.0f, 30.0f, 31.0f )); Assert.That(() => value.X, Is.EqualTo(Vector4.Create(16.0f, 17.0f, 18.0f, 19.0f))); Assert.That(() => value.Y, Is.EqualTo(Vector4.Create(20.0f, 21.0f, 22.0f, 23.0f))); Assert.That(() => value.Z, Is.EqualTo(Vector4.Create(24.0f, 25.0f, 26.0f, 27.0f))); Assert.That(() => value.W, Is.EqualTo(Vector4.Create(28.0f, 29.0f, 30.0f, 31.0f))); } /// <summary>Provides validation of the <see cref="Matrix4x4.Determinant" /> property.</summary> [Test] public static void DeterminantTest() { Assert.That(() => Matrix4x4.Create( UnitX, Vector128.Create(0.0f, 2.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 3.0f, 0.0f), Vector128.Create(1.0f, 2.0f, 3.0f, 1.0f) ).Determinant, Is.EqualTo(6.0f)); } /// <summary>Provides validation of the <see cref="Matrix4x4.op_Equality" /> method.</summary> [Test] public static void OpEqualityTest() { #pragma warning disable CS1718 Assert.That(() => Matrix4x4.Identity == Matrix4x4.Identity, Is.True ); #pragma warning restore CS1718 Assert.That(() => Matrix4x4.Identity == Matrix4x4.Zero, Is.False ); } /// <summary>Provides validation of the <see cref="Matrix4x4.op_Inequality" /> method.</summary> [Test] public static void OpInequalityTest() { #pragma warning disable CS1718 Assert.That(() => Matrix4x4.Identity != Matrix4x4.Identity, Is.False ); #pragma warning restore CS1718 Assert.That(() => Matrix4x4.Identity != Matrix4x4.Zero, Is.True ); } /// <summary>Provides validation of the <see cref="Matrix4x4.op_Multiply" /> method.</summary> [Test] public static void OpMultiplyTest() { Assert.That(() => Matrix4x4.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, 0.5f)) * Matrix4x4.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitY, 0.5f)), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.87758255f, +0.00000000f, -0.47942555f, 0.0f), Vector128.Create(0.22984886f, +0.87758255f, +0.42073550f, 0.0f), Vector128.Create(0.42073550f, -0.47942555f, +0.77015114f, 0.0f), UnitW )) ); } // OpMultiply /// <summary>Provides validation of the <see cref="Matrix4x4.CompareEqualAll(Matrix4x4, in Matrix4x4)" /> method.</summary> [Test] public static void CompareEqualAllTest() { Assert.That(() => Matrix4x4.CompareEqualAll(Matrix4x4.Identity, Matrix4x4.Identity), Is.True ); Assert.That(() => Matrix4x4.CompareEqualAll(Matrix4x4.Identity, Matrix4x4.Zero), Is.False ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromAffineTransform(AffineTransform, Vector3)" /> method.</summary> [Test] public static void CreateFromAffineTransform() { Assert.That(() => Matrix4x4.CreateFromAffineTransform(AffineTransform.Create(Quaternion.CreateFromAxisAngle(Vector3.UnitX, 0.5f), Vector3.One, Vector3.Zero)), Is.EqualTo(Matrix4x4.Create( UnitX, Vector128.Create(0.0f, +0.87758255f, 0.47942555f, 0.0f), Vector128.Create(0.0f, -0.47942555f, 0.87758255f, 0.0f), UnitW )) ); Assert.That(() => Matrix4x4.CreateFromAffineTransform(AffineTransform.Create(Quaternion.Identity, Vector3.Create(1.0f, 2.0f, 3.0f), Vector3.Zero)), Is.EqualTo(Matrix4x4.Create( UnitX, Vector128.Create(0.0f, 2.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 3.0f, 0.0f), UnitW )) ); Assert.That(() => Matrix4x4.CreateFromAffineTransform(AffineTransform.Create(Quaternion.Identity, Vector3.One, Vector3.Create(1.0f, 2.0f, 3.0f))), Is.EqualTo(Matrix4x4.Create( UnitX, UnitY, UnitZ, Vector128.Create(1.0f, 2.0f, 3.0f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromQuaternion" /> method.</summary> [Test] public static void CreateFromQuaternionTest() { Assert.That(() => Matrix4x4.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, 0.5f)), Is.EqualTo(Matrix4x4.Create( UnitX, Vector128.Create(0.0f, +0.87758255f, 0.47942555f, 0.0f), Vector128.Create(0.0f, -0.47942555f, 0.87758255f, 0.0f), UnitW )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromRotationX" /> method.</summary> [Test] public static void CreateFromRotationXTest() { Assert.That(() => Matrix4x4.CreateFromRotationX(0.5f), Is.EqualTo(Matrix4x4.Create( UnitX, Vector128.Create(0.0f, +0.87758255f, 0.47942555f, 0.0f), Vector128.Create(0.0f, -0.47942555f, 0.87758255f, 0.0f), UnitW )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromRotationY" /> method.</summary> [Test] public static void CreateFromRotationYTest() { Assert.That(() => Matrix4x4.CreateFromRotationY(0.5f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.87758255f, 0.0f, -0.47942555f, 0.0f), UnitY, Vector128.Create(0.47942555f, 0.0f, +0.87758255f, 0.0f), UnitW )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromRotationZ" /> method.</summary> [Test] public static void CreateFromRotationZTest() { Assert.That(() => Matrix4x4.CreateFromRotationZ(0.5f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(+0.87758255f, 0.47942555f, 0.0f, 0.0f), Vector128.Create(-0.47942555f, 0.87758255f, 0.0f, 0.0f), UnitZ, UnitW )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromScale" /> method.</summary> [Test] public static void CreateFromScaleTest() { Assert.That(() => Matrix4x4.CreateFromScale(Vector3.Create(1.0f, 2.0f, 3.0f)), Is.EqualTo(Matrix4x4.Create( UnitX, Vector128.Create(0.0f, 2.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 3.0f, 0.0f), UnitW )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateFromTranslation" /> method.</summary> [Test] public static void CreateFromTranslationTest() { Assert.That(() => Matrix4x4.CreateFromTranslation(Vector3.Create(1.0f, 2.0f, 3.0f)), Is.EqualTo(Matrix4x4.Create( UnitX, UnitY, UnitZ, Vector128.Create(1.0f, 2.0f, 3.0f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateLookAtLH" /> method.</summary> [Test] public static void CreateLookAtLHTest() { Assert.That(() => Matrix4x4.CreateLookAtLH(+Vector3.UnitZ, Vector3.Zero, Vector3.UnitY), Is.EqualTo(Matrix4x4.Create( Negate(UnitX), UnitY, Negate(UnitZ), UnitW.WithZ(+1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateLookAtRH" /> method.</summary> [Test] public static void CreateLookAtRHTest() { Assert.That(() => Matrix4x4.CreateLookAtRH(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY), Is.EqualTo(Matrix4x4.Create( UnitX, UnitY, UnitZ, UnitW.WithZ(-1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateLookToLH" /> method.</summary> [Test] public static void CreateLookToLHTest() { Assert.That(() => Matrix4x4.CreateLookToLH(Vector3.UnitZ, -Vector3.UnitZ, Vector3.UnitY), Is.EqualTo(Matrix4x4.Create( Negate(UnitX), UnitY, Negate(UnitZ), UnitW.WithZ(+1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateLookToRH" /> method.</summary> [Test] public static void CreateLookToRHTest() { Assert.That(() => Matrix4x4.CreateLookToRH(Vector3.UnitZ, -Vector3.UnitZ, Vector3.UnitY), Is.EqualTo(Matrix4x4.Create( UnitX, UnitY, UnitZ, UnitW.WithZ(-1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateOrthographicLH" /> method.</summary> [Test] public static void CreateOrthographicLHTest() { Assert.That(() => Matrix4x4.CreateOrthographicLH(1920.0f, 1080.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.0010416667f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0018518518f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 0.001000001f, 0.0f), Vector128.Create(0.0f, 0.0f, -1.000001E-06f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateOrthographicRH" /> method.</summary> [Test] public static void CreateOrthographicRHTest() { Assert.That(() => Matrix4x4.CreateOrthographicRH(1920.0f, 1080.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.0010416667f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0018518518f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f), Vector128.Create(0.0f, 0.0f, -1.000001E-06f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateOrthographicOffCenterLH" /> method.</summary> [Test] public static void CreateOrthographicOffCenterLHTest() { Assert.That(() => Matrix4x4.CreateOrthographicOffCenterLH(-960.0f, +960.0f, +540.0f, -540.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.0010416667f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, -0.0018518518f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 0.001000001f, 0.0f), Vector128.Create(-0.0f, 0.0f, -1.000001E-06f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreateOrthographicOffCenterRH" /> method.</summary> [Test] public static void CreateOrthographicOffCenterRHTest() { Assert.That(() => Matrix4x4.CreateOrthographicOffCenterRH(-960.0f, +960.0f, +540.0f, -540.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.0010416667f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, -0.0018518518f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f), Vector128.Create(-0.0f, 0.0f, -1.000001E-06f, 1.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveLH" /> method.</summary> [Test] public static void CreatePerspectiveLHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveLH(1920.0f, 1080.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(1.0416667E-06f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 1.851852E-06f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 1.000001f, 1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveRH" /> method.</summary> [Test] public static void CreatePerspectiveRHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveRH(1920.0f, 1080.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(1.0416667E-06f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 1.851852E-06f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, -1.000001f, -1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveFieldOfViewLH" /> method.</summary> [Test] public static void CreatePerspectiveFieldOfViewLHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveFieldOfViewLH(1.2217305f, 1.7777778f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.8033333f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 1.428148f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 1.000001f, 1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveFieldOfViewRH" /> method.</summary> [Test] public static void CreatePerspectiveFieldOfViewRHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveFieldOfViewRH(1.2217305f, 1.7777778f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(0.8033333f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 1.428148f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, -1.000001f, -1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveOffCenterLH" /> method.</summary> [Test] public static void CreatePerspectiveOffCenterLHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveOffCenterLH(-960.0f, +960.0f, +540.0f, -540.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(1.0416668E-06f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, -1.851852E-06f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 1.000001f, 1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.CreatePerspectiveOffCenterRH" /> method.</summary> [Test] public static void CreatePerspectiveOffCenterRHTest() { Assert.That(() => Matrix4x4.CreatePerspectiveOffCenterRH(-960.0f, +960.0f, +540.0f, -540.0f, 0.001f, 1000.0f), Is.EqualTo(Matrix4x4.Create( Vector128.Create(1.0416668E-06f, 0.0f, 0.0f, 0.0f), Vector128.Create(0.0f, -1.851852E-06f, 0.0f, 0.0f), Vector128.Create(0.0f, -0.0f, -1.000001f, -1.0f), Vector128.Create(0.0f, 0.0f, -0.001000001f, 0.0f) )) ); } /// <summary>Provides validation of the <see cref="Matrix4x4.Inverse(Matrix4x4, out float)" /> method.</summary> [Test] public static void InverseTest() { Assert.That(() => { var matrix = Matrix4x4.Create( UnitX, Vector128.Create(0.0f, 2.0f, 0.0f, 0.0f), Vector128.Create(0.0f, 0.0f, 3.0f, 0.0f), Vector128.Create(1.0f, 2.0f, 3.0f, 1.0f) ); return Matrix4x4.Inverse(matrix, out _); }, Is.EqualTo(Matrix4x4.Create( Vector128.Create(+1.0f, +0.0f, +0.00000000f, 0.0f), Vector128.Create(+0.0f, +0.5f, +0.00000000f, 0.0f), Vector128.Create(+0.0f, +0.0f, +0.33333334f, 0.0f), Vector128.Create(-1.0f, -1.0f, -1.00000000f, 1.0f) ))); } /// <summary>Provides validation of the <see cref="Matrix4x4.IsAnyInfinity(Matrix4x4)" /> method.</summary> [Test] public static void IsAnyInfinityTest() { Assert.That(() => { var matrix = Matrix4x4.Identity; matrix.W = Vector4.Create(0.0f, 0.0f, 0.0f, float.PositiveInfinity); return Matrix4x4.IsAnyInfinity(matrix); }, Is.True); Assert.That(() => { var matrix = Matrix4x4.Identity; matrix.W = Vector4.Create(0.0f, 0.0f, 0.0f, float.NegativeInfinity); return Matrix4x4.IsAnyInfinity(matrix); }, Is.True); Assert.That(() => Matrix4x4.IsAnyInfinity(Matrix4x4.Identity), Is.False ); } /// <summary>Provides validation of the <see cref="Matrix4x4.IsAnyNaN(Matrix4x4)" /> method.</summary> [Test] public static void IsAnyNaNTest() { Assert.That(() => { var matrix = Matrix4x4.Identity; matrix.W = Vector4.Create(0.0f, 0.0f, 0.0f, float.NaN); return Matrix4x4.IsAnyNaN(matrix); }, Is.True); Assert.That(() => Matrix4x4.IsAnyNaN(Matrix4x4.Identity), Is.False ); } /// <summary>Provides validation of the <see cref="Matrix4x4.IsIdentity(Matrix4x4)" /> method.</summary> [Test] public static void IsIdentityTest() { Assert.That(() => Matrix4x4.IsIdentity(Matrix4x4.Identity), Is.True ); Assert.That(() => Matrix4x4.IsIdentity(Matrix4x4.Zero), Is.False ); } // Transpose /// <summary>Provides validation of the <see cref="Matrix4x4.AsSystemMatrix4x4" /> method.</summary> [Test] public static void AsSystemMatrix4x4Test() { Assert.That(() => Matrix4x4.Identity.AsSystemMatrix4x4(), Is.EqualTo(SysMatrix4x4.Identity) ); } }
using Signum.Utilities.Reflection; using Signum.Engine.Maps; using Signum.Entities.Basics; using System.Text.RegularExpressions; using Signum.Entities.DynamicQuery; namespace Signum.Engine.DynamicQuery; public static class AutocompleteUtils { public static List<Lite<Entity>> FindLiteLike(Implementations implementations, string subString, int count) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike"); try { using (ExecutionMode.UserInterface()) return FindLiteLike(implementations.Types, subString, count); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static async Task<List<Lite<Entity>>> FindLiteLikeAsync(Implementations implementations, string subString, int count, CancellationToken cancellationToken) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike"); try { using (ExecutionMode.UserInterface()) return await FindLiteLikeAsync(implementations.Types, subString, count, cancellationToken); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } private static bool TryParsePrimaryKey(string value, Type type, out PrimaryKey id) { var match = Regex.Match(value, "^id[:]?(.*)", RegexOptions.IgnoreCase); if (match.Success) return PrimaryKey.TryParse(match.Groups[1].ToString(), type, out id); id = default; return false; } static List<Lite<Entity>> FindLiteLike(IEnumerable<Type> types, string subString, int count) { if (subString == null) subString = ""; types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null); List<Lite<Entity>> results = new List<Lite<Entity>>(); foreach (var t in types) { if (TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var lite = giLiteById.GetInvoker(t).Invoke(id); if (lite != null) { results.Add(lite); if (results.Count >= count) return results; } } } foreach (var t in types) { if (!TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var parts = subString.SplitParts(); results.AddRange(giLiteContaining.GetInvoker(t)(parts, count - results.Count)); if (results.Count >= count) return results; } } return results; } private static async Task<List<Lite<Entity>>> FindLiteLikeAsync(IEnumerable<Type> types, string subString, int count, CancellationToken cancellationToken) { if (subString == null) subString = ""; types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null); List<Lite<Entity>> results = new List<Lite<Entity>>(); foreach (var t in types) { if (TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var lite = await giLiteByIdAsync.GetInvoker(t).Invoke(id, cancellationToken); if (lite != null) { results.Add(lite); if (results.Count >= count) return results; } } } foreach (var t in types) { if (!TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var parts = subString.SplitParts(); var list = await giLiteContainingAsync.GetInvoker(t)(parts, count - results.Count, cancellationToken); results.AddRange(list); if (results.Count >= count) return results; } } return results; } static GenericInvoker<Func<PrimaryKey, Lite<Entity>?>> giLiteById = new(id => LiteById<TypeEntity>(id)); static Lite<Entity>? LiteById<T>(PrimaryKey id) where T : Entity { return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefault(); } static GenericInvoker<Func<PrimaryKey, CancellationToken, Task<Lite<Entity>>>> giLiteByIdAsync = new((id, token) => LiteByIdAsync<TypeEntity>(id, token)); static Task<Lite<Entity>> LiteByIdAsync<T>(PrimaryKey id, CancellationToken token) where T : Entity { return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefaultAsync(token).ContinueWith(t => (Lite<Entity>)t.Result); } static GenericInvoker<Func<string[], int, List<Lite<Entity>>>> giLiteContaining = new((parts, c) => LiteContaining<TypeEntity>(parts, c)); static List<Lite<Entity>> LiteContaining<T>(string[] parts, int count) where T : Entity { return Database.Query<T>() .Where(a => a.ToString().ContainsAllParts(parts)) .OrderBy(a => a.ToString().Length) .Select(a => a.ToLite()) .Take(count) .AsEnumerable() .Cast<Lite<Entity>>() .ToList(); } static GenericInvoker<Func<string[], int, CancellationToken, Task<List<Lite<Entity>>>>> giLiteContainingAsync = new((parts, c, token) => LiteContaining<TypeEntity>(parts, c, token)); static async Task<List<Lite<Entity>>> LiteContaining<T>(string[] parts, int count, CancellationToken token) where T : Entity { var list = await Database.Query<T>() .Where(a => a.ToString().ContainsAllParts(parts)) .OrderBy(a => a.ToString().Length) .Select(a => a.ToLite()) .Take(count) .ToListAsync(token); return list.Cast<Lite<Entity>>().ToList(); } public static List<Lite<Entity>> FindAllLite(Implementations implementations) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite"); try { using (ExecutionMode.UserInterface()) return implementations.Types.SelectMany(type => Database.RetrieveAllLite(type)).ToList(); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static async Task<List<Lite<Entity>>> FindAllLiteAsync(Implementations implementations, CancellationToken token) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite"); try { using (ExecutionMode.UserInterface()) { var tasks = implementations.Types.Select(type => Database.RetrieveAllLiteAsync(type, token)).ToList(); var list = await Task.WhenAll(tasks); return list.SelectMany(li => li).ToList(); } } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static List<Lite<T>> Autocomplete<T>(this IQueryable<Lite<T>> query, string subString, int count) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T>? entity = query.SingleOrDefaultEx(e => e.Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); results.AddRange(query.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count)); return results; } } public static async Task<List<Lite<T>>> AutocompleteAsync<T>(this IQueryable<Lite<T>> query, string subString, int count, CancellationToken token) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T> entity = await query.SingleOrDefaultAsync(e => e.Id == id, token); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = await query.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count) .ToListAsync(token); results.AddRange(list); return results; } } public static List<Lite<T>> Autocomplete<T>(this IEnumerable<Lite<T>> collection, string subString, int count) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T>? entity = collection.SingleOrDefaultEx(e => e.Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = collection.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count); results.AddRange(list); return results; } } public static string[] SplitParts(this string str) { if (FilterCondition.ToLowerString()) return str.Trim().ToLower().SplitNoEmpty(' '); return str.Trim().SplitNoEmpty(' '); } [AutoExpressionField] public static bool ContainsAllParts(this string str, string[] parts) => As.Expression(() => FilterCondition.ToLowerString() ? str.ToLower().ContainsAll(parts) : str.ContainsAll(parts)); }
// 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.Globalization; using System.IO; using System.Text; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class BinaryFormatterWriter { private const int ChunkSize = 4096; private readonly Stream _outputStream; private readonly FormatterTypeStyle _formatterTypeStyle; private readonly ObjectWriter _objectWriter = null; private readonly BinaryWriter _dataWriter = null; private int _consecutiveNullArrayEntryCount = 0; private Dictionary<string, ObjectMapInfo> _objectMapTable; private BinaryObject _binaryObject; private BinaryObjectWithMap _binaryObjectWithMap; private BinaryObjectWithMapTyped _binaryObjectWithMapTyped; private BinaryObjectString _binaryObjectString; private BinaryArray _binaryArray; private byte[] _byteBuffer = null; private MemberPrimitiveUnTyped _memberPrimitiveUnTyped; private MemberPrimitiveTyped _memberPrimitiveTyped; private ObjectNull _objectNull; private MemberReference _memberReference; private BinaryAssembly _binaryAssembly; internal BinaryFormatterWriter(Stream outputStream, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle) { _outputStream = outputStream; _formatterTypeStyle = formatterTypeStyle; _objectWriter = objectWriter; _dataWriter = new BinaryWriter(outputStream, Encoding.UTF8); } internal void WriteBegin() { } internal void WriteEnd() { _dataWriter.Flush(); } internal void WriteBoolean(bool value) => _dataWriter.Write(value); internal void WriteByte(byte value) => _dataWriter.Write(value); private void WriteBytes(byte[] value) => _dataWriter.Write(value); private void WriteBytes(byte[] byteA, int offset, int size) => _dataWriter.Write(byteA, offset, size); internal void WriteChar(char value) => _dataWriter.Write(value); internal void WriteChars(char[] value) => _dataWriter.Write(value); internal void WriteDecimal(decimal value) => WriteString(value.ToString(CultureInfo.InvariantCulture)); internal void WriteSingle(float value) => _dataWriter.Write(value); internal void WriteDouble(double value) => _dataWriter.Write(value); internal void WriteInt16(short value) => _dataWriter.Write(value); internal void WriteInt32(int value) => _dataWriter.Write(value); internal void WriteInt64(long value) => _dataWriter.Write(value); internal void WriteSByte(sbyte value) => WriteByte((byte)value); internal void WriteString(string value) => _dataWriter.Write(value); internal void WriteTimeSpan(TimeSpan value) => WriteInt64(value.Ticks); internal void WriteDateTime(DateTime value) => WriteInt64(value.Ticks); // in desktop, this uses ToBinaryRaw internal void WriteUInt16(ushort value) => _dataWriter.Write(value); internal void WriteUInt32(uint value) => _dataWriter.Write(value); internal void WriteUInt64(ulong value) => _dataWriter.Write(value); internal void WriteObjectEnd(NameInfo memberNameInfo, NameInfo typeNameInfo) { } internal void WriteSerializationHeaderEnd() { var record = new MessageEnd(); record.Write(this); } internal void WriteSerializationHeader(int topId, int headerId, int minorVersion, int majorVersion) { var record = new SerializationHeaderRecord(BinaryHeaderEnum.SerializedStreamHeader, topId, headerId, minorVersion, majorVersion); record.Write(this); } internal void WriteObject(NameInfo nameInfo, NameInfo typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos) { InternalWriteItemNull(); int assemId; int objectId = (int)nameInfo._objectId; string objectName = objectId < 0 ? objectName = typeNameInfo.NIname : // Nested Object objectName = nameInfo.NIname; // Non-Nested if (_objectMapTable == null) { _objectMapTable = new Dictionary<string, ObjectMapInfo>(); } ObjectMapInfo objectMapInfo; if (_objectMapTable.TryGetValue(objectName, out objectMapInfo) && objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes)) { // Object if (_binaryObject == null) { _binaryObject = new BinaryObject(); } _binaryObject.Set(objectId, objectMapInfo._objectId); _binaryObject.Write(this); } else if (!typeNameInfo._transmitTypeOnObject) { // ObjectWithMap if (_binaryObjectWithMap == null) { _binaryObjectWithMap = new BinaryObjectWithMap(); } // BCL types are not placed into table assemId = (int)typeNameInfo._assemId; _binaryObjectWithMap.Set(objectId, objectName, numMembers, memberNames, assemId); _binaryObjectWithMap.Write(this); if (objectMapInfo == null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } } else { // ObjectWithMapTyped var binaryTypeEnumA = new BinaryTypeEnum[numMembers]; var typeInformationA = new object[numMembers]; var assemIdA = new int[numMembers]; for (int i = 0; i < numMembers; i++) { object typeInformation = null; binaryTypeEnumA[i] = BinaryTypeConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, _objectWriter, out typeInformation, out assemId); typeInformationA[i] = typeInformation; assemIdA[i] = assemId; } if (_binaryObjectWithMapTyped == null) { _binaryObjectWithMapTyped = new BinaryObjectWithMapTyped(); } // BCL types are not placed in table assemId = (int)typeNameInfo._assemId; _binaryObjectWithMapTyped.Set(objectId, objectName, numMembers, memberNames, binaryTypeEnumA, typeInformationA, assemIdA, assemId); _binaryObjectWithMapTyped.Write(this); if (objectMapInfo == null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } } } internal void WriteObjectString(int objectId, string value) { InternalWriteItemNull(); if (_binaryObjectString == null) { _binaryObjectString = new BinaryObjectString(); } _binaryObjectString.Set(objectId, value); _binaryObjectString.Write(this); } internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum; var lengthA = new int[1]; lengthA[0] = length; int[] lowerBoundA = null; object typeInformation = null; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Single; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.SingleOffset; lowerBoundA = new int[1]; lowerBoundA[0] = lowerBound; } int assemId; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo( arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); if (Converter.IsWriteAsByteArray(arrayElemTypeNameInfo._primitiveTypeEnum) && (lowerBound == 0)) { //array is written out as an array of bytes if (arrayElemTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Byte) { WriteBytes((byte[])array); } else if (arrayElemTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Char) { WriteChars((char[])array); } else { WriteArrayAsBytes(array, Converter.TypeLength(arrayElemTypeNameInfo._primitiveTypeEnum)); } } } private void WriteArrayAsBytes(Array array, int typeLength) { InternalWriteItemNull(); int byteLength = array.Length * typeLength; int arrayOffset = 0; if (_byteBuffer == null) { _byteBuffer = new byte[ChunkSize]; } while (arrayOffset < array.Length) { int numArrayItems = Math.Min(ChunkSize / typeLength, array.Length - arrayOffset); int bufferUsed = numArrayItems * typeLength; Buffer.BlockCopy(array, arrayOffset * typeLength, _byteBuffer, 0, bufferUsed); if (!BitConverter.IsLittleEndian) { // we know that we are writing a primitive type, so just do a simple swap Debug.Fail("Re-review this code if/when we start running on big endian systems"); for (int i = 0; i < bufferUsed; i += typeLength) { for (int j = 0; j < typeLength / 2; j++) { byte tmp = _byteBuffer[i + j]; _byteBuffer[i + j] = _byteBuffer[i + typeLength - 1 - j]; _byteBuffer[i + typeLength - 1 - j] = tmp; } } } WriteBytes(_byteBuffer, 0, bufferUsed); arrayOffset += numArrayItems; } } internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum; var lengthA = new int[1]; lengthA[0] = length; int[] lowerBoundA = null; object typeInformation = null; int assemId = 0; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Jagged; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.JaggedOffset; lowerBoundA = new int[1]; lowerBoundA[0] = lowerBound; } BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); } internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular; object typeInformation = null; int assemId = 0; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } for (int i = 0; i < rank; i++) { if (lowerBoundA[i] != 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.RectangularOffset; break; } } _binaryArray.Set((int)arrayNameInfo._objectId, rank, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); } internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA) { InternalWriteItemNull(); WriteSingleArray(memberNameInfo, arrayNameInfo, objectInfo, arrayElemTypeNameInfo, length, lowerBound, byteA); } internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object value) { InternalWriteItemNull(); InternalPrimitiveTypeE typeInformation = typeNameInfo._primitiveTypeEnum; // Writes Members with primitive values if (memberNameInfo._transmitTypeOnMember) { if (_memberPrimitiveTyped == null) { _memberPrimitiveTyped = new MemberPrimitiveTyped(); } _memberPrimitiveTyped.Set(typeInformation, value); _memberPrimitiveTyped.Write(this); } else { if (_memberPrimitiveUnTyped == null) { _memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); } _memberPrimitiveUnTyped.Set(typeInformation, value); _memberPrimitiveUnTyped.Write(this); } } internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) { InternalWriteItemNull(); if (_objectNull == null) { _objectNull = new ObjectNull(); } if (!memberNameInfo._isArrayItem) { _objectNull.SetNullCount(1); _objectNull.Write(this); _consecutiveNullArrayEntryCount = 0; } } internal void WriteMemberObjectRef(NameInfo memberNameInfo, int idRef) { InternalWriteItemNull(); if (_memberReference == null) { _memberReference = new MemberReference(); } _memberReference.Set(idRef); _memberReference.Write(this); } internal void WriteMemberNested(NameInfo memberNameInfo) { InternalWriteItemNull(); } internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string value) { InternalWriteItemNull(); WriteObjectString((int)typeNameInfo._objectId, value); } internal void WriteItem(NameInfo itemNameInfo, NameInfo typeNameInfo, object value) { InternalWriteItemNull(); WriteMember(itemNameInfo, typeNameInfo, value); } internal void WriteNullItem(NameInfo itemNameInfo, NameInfo typeNameInfo) { _consecutiveNullArrayEntryCount++; InternalWriteItemNull(); } internal void WriteDelayedNullItem() { _consecutiveNullArrayEntryCount++; } internal void WriteItemEnd() => InternalWriteItemNull(); private void InternalWriteItemNull() { if (_consecutiveNullArrayEntryCount > 0) { if (_objectNull == null) { _objectNull = new ObjectNull(); } _objectNull.SetNullCount(_consecutiveNullArrayEntryCount); _objectNull.Write(this); _consecutiveNullArrayEntryCount = 0; } } internal void WriteItemObjectRef(NameInfo nameInfo, int idRef) { InternalWriteItemNull(); WriteMemberObjectRef(nameInfo, idRef); } internal void WriteAssembly(Type type, string assemblyString, int assemId, bool isNew) { //If the file being tested wasn't built as an assembly, then we're going to get null back //for the assembly name. This is very unfortunate. InternalWriteItemNull(); if (assemblyString == null) { assemblyString = string.Empty; } if (isNew) { if (_binaryAssembly == null) { _binaryAssembly = new BinaryAssembly(); } _binaryAssembly.Set(assemId, assemblyString); _binaryAssembly.Write(this); } } // Method to write a value onto a stream given its primitive type code internal void WriteValue(InternalPrimitiveTypeE code, object value) { switch (code) { case InternalPrimitiveTypeE.Boolean: WriteBoolean(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Byte: WriteByte(Convert.ToByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Char: WriteChar(Convert.ToChar(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Double: WriteDouble(Convert.ToDouble(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int16: WriteInt16(Convert.ToInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int32: WriteInt32(Convert.ToInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int64: WriteInt64(Convert.ToInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.SByte: WriteSByte(Convert.ToSByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Single: WriteSingle(Convert.ToSingle(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt16: WriteUInt16(Convert.ToUInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt32: WriteUInt32(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt64: WriteUInt64(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Decimal: WriteDecimal(Convert.ToDecimal(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value); break; case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value); break; default: throw new SerializationException(SR.Format(SR.Serialization_TypeCode, code.ToString())); } } private sealed class ObjectMapInfo { internal readonly int _objectId; private readonly int _numMembers; private readonly string[] _memberNames; private readonly Type[] _memberTypes; internal ObjectMapInfo(int objectId, int numMembers, string[] memberNames, Type[] memberTypes) { _objectId = objectId; _numMembers = numMembers; _memberNames = memberNames; _memberTypes = memberTypes; } internal bool IsCompatible(int numMembers, string[] memberNames, Type[] memberTypes) { if (_numMembers != numMembers) { return false; } for (int i = 0; i < numMembers; i++) { if (!(_memberNames[i].Equals(memberNames[i]))) { return false; } if ((memberTypes != null) && (_memberTypes[i] != memberTypes[i])) { return false; } } return true; } } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Xml; using System.IO; namespace MyGUI.Sharp { public partial class Gui { #region Instance private static Gui mInstance = new Gui(); public static Gui Instance { get { return mInstance; } } #endregion #region CreateWidget public T CreateWidget<T>(string _skin, IntCoord _coord, Align _align, string _layer) where T : class { T type = System.Activator.CreateInstance<T>(); BaseWidget widget = type as BaseWidget; widget.CreateWidget(null, WidgetStyle.Overlapped, _skin, _coord, _align, _layer, ""); return type; } public T CreateWidget<T>(string _skin, IntCoord _coord, Align _align, string _layer, string _name) where T : class { T type = System.Activator.CreateInstance<T>(); BaseWidget widget = type as BaseWidget; widget.CreateWidget(null, WidgetStyle.Overlapped, _skin, _coord, _align, _layer, _name); return type; } #endregion #region LoadLayout public List<Widget> LoadLayout(string _file) { return LoadLayout(_file, null, ""); } public List<Widget> LoadLayout(string _file, string _prefix) { return LoadLayout(_file, null, _prefix); } public List<Widget> LoadLayout(string _file, Widget _parent) { return LoadLayout(_file, _parent, ""); } [DllImport("MyGUI.Export.dll", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportGui_GetPath( [MarshalAs(UnmanagedType.LPStr)] string _filename ); public List<Widget> LoadLayout(string _file, Widget _parent, string _prefix) { List<Widget> widgets = new List<Widget>(); string filename = Marshal.PtrToStringAnsi( ExportGui_GetPath(_file) ); if (filename == "") return widgets; XmlDocument mfDocument = new XmlDocument(); try { mfDocument.Load(filename); } catch (FileNotFoundException) { return widgets; } foreach (XmlNode node in mfDocument) { if ("MyGUI" != node.Name) continue; if ("Layout" != node.Attributes["type"].Value) continue; foreach (XmlNode widget_node in node) { if ("Widget" != widget_node.Name) continue; ParseWidget(widgets, widget_node, _parent, null, _prefix); } } return widgets; } private void ParseWidget(List<Widget> _widgets, XmlNode _node, Widget _parent, Widget _root, string _prefix) { string style = "", type = "", skin = "", name = "", layer = "", align = "", position = ""; foreach (XmlAttribute attribute in _node.Attributes) { switch (attribute.Name) { case "style": style = attribute.Value; break; case "type": type = attribute.Value; break; case "skin": skin = attribute.Value; break; case "name": name = attribute.Value; break; case "layer": layer = attribute.Value; break; case "align": align = attribute.Value; break; case "position": position = attribute.Value; break; } if (type == "Sheet") type = "TabItem"; } if ((0 == type.Length) || (0 == skin.Length)) { return; } if ((0 != name.Length) && (0 != _prefix.Length)) name = _prefix + name; string[] coord = position.Split(); WidgetStyle wstyle = WidgetStyle.Overlapped; if (_parent != null) { layer = ""; wstyle = (style != string.Empty) ? (WidgetStyle)Enum.Parse(typeof(WidgetStyle), style) : WidgetStyle.Child; } Align walign = Align.Default; if (align != string.Empty) { walign = Align.Center; string[] mass = align.Split(); foreach (string item in mass) walign |= (Align)Enum.Parse(typeof(Align), item); } Widget widget = (Widget)mMapCreator[type]( _parent, wstyle, skin, ((coord.Length == 4) ? new IntCoord(int.Parse(coord[0]), int.Parse(coord[1]), int.Parse(coord[2]), int.Parse(coord[3])) : new IntCoord()), walign, layer, name); if (null == _root) { _root = widget; _widgets.Add(_root); } foreach (XmlNode node in _node) { if ("Widget" == node.Name) { ParseWidget(_widgets, node, widget, _root, _prefix); } else if ("Property" == node.Name) { string key = "", value = ""; foreach (XmlAttribute attribute in node.Attributes) { if ("key" == attribute.Name) key = attribute.Value; else if ("value" == attribute.Name) value = attribute.Value; } if ((0 == key.Length) || (0 == value.Length)) continue; SetProperty(widget, key, value); } else if ("UserString" == node.Name) { string key = "", value = ""; foreach (XmlAttribute attribute in node.Attributes) { if ("key" == attribute.Name) key = attribute.Value; else if ("value" == attribute.Name) value = attribute.Value; } if ((0 == key.Length) || (0 == value.Length)) continue; widget.SetUserString(key, value); if (EventParserUserData != null) EventParserUserData(widget, key, value); } } } [DllImport("MyGUI.Export.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void ExportGui_SetProperty( IntPtr _widget, [MarshalAs(UnmanagedType.LPStr)] string _key , [MarshalAs(UnmanagedType.LPStr)] string _value ); void SetProperty(Widget _widget, string _key, string _value) { ExportGui_SetProperty(_widget.GetNative(), _key, _value); } #endregion #region LoadResource [DllImport("MyGUI.Export.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void ExportGui_LoadResource( [MarshalAs(UnmanagedType.LPStr)] string _source ); public void LoadResource(string _source) { ExportGui_LoadResource(_source); } #endregion #region EventParserUserData public delegate void HandleParserUserData(Widget _widget, string _key, string _value); public event Gui.HandleParserUserData EventParserUserData; #endregion #region WrapperCreator delegate BaseWidget HandleWrapWidget(BaseWidget _parent, IntPtr _widget); static Dictionary<string, HandleWrapWidget> mMapWrapper = new Dictionary<string, HandleWrapWidget>(); delegate BaseWidget HandleCreateWidget(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name); static Dictionary<string, HandleCreateWidget> mMapCreator = new Dictionary<string, HandleCreateWidget>(); class WrapperCreator { [return: MarshalAs(UnmanagedType.Interface)] public delegate BaseWidget HandleDelegate([MarshalAs(UnmanagedType.LPStr)]string _type, [MarshalAs(UnmanagedType.Interface)]BaseWidget _parent, IntPtr _widget); [DllImport("MyGUI.Export.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void ExportGui_SetCreatorWrapps(HandleDelegate _delegate); static HandleDelegate mDelegate; public WrapperCreator() { mDelegate = new HandleDelegate(OnRequest); ExportGui_SetCreatorWrapps(mDelegate); InitialiseWidgetCreator(); } BaseWidget OnRequest(string _type, BaseWidget _parent, IntPtr _widget) { return mMapWrapper[_type](_parent, _widget); } } static WrapperCreator mWrapperCreator = new WrapperCreator(); #endregion #region GetNativeByWrapper class GetNativeByWrapper { public delegate IntPtr HandleDelegate([MarshalAs(UnmanagedType.Interface)]BaseWidget _wrapper); [DllImport("MyGUI.Export.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void ExportGui_SetGetNativeByWrapper(HandleDelegate _delegate); static HandleDelegate mDelegate; public GetNativeByWrapper() { mDelegate = new HandleDelegate(OnRequest); ExportGui_SetGetNativeByWrapper(mDelegate); } IntPtr OnRequest(BaseWidget _wrapper) { return _wrapper == null ? IntPtr.Zero : _wrapper.GetNative(); } } static GetNativeByWrapper mGetNativeByWrapper = new GetNativeByWrapper(); #endregion } }
// Copyright (c) 2017 Jean Ressouche @SouchProd. All rights reserved. // https://github.com/souchprod/SouchProd.EntityFrameworkCore.Firebird // This code inherit from the .Net Foundation Entity Core repository (Apache licence) // and from the Pomelo Foundation Mysql provider repository (MIT licence). // Licensed under the MIT. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Data; using System.Text.RegularExpressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Utilities; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Storage.Internal { public class FbTypeMapper : RelationalTypeMapper { private static readonly Regex TypeRe = new Regex(@"([a-z0-9]+)\s*?(?:\(\s*(\d+)?\s*\))?\s*(unsigned)?", RegexOptions.IgnoreCase); // boolean private readonly FbBoolTypeMapping _bit = new FbBoolTypeMapping("smallint", DbType.SByte); // integers private readonly SByteTypeMapping _tinyint = new SByteTypeMapping("smallint", DbType.SByte); private readonly ByteTypeMapping _utinyint = new ByteTypeMapping("smallint", DbType.Byte); private readonly ShortTypeMapping _smallint = new ShortTypeMapping("smallint", DbType.Int16); private readonly UShortTypeMapping _usmallint = new UShortTypeMapping("smallint", DbType.UInt16); private readonly IntTypeMapping _int = new IntTypeMapping("integer", DbType.Int32); private readonly UIntTypeMapping _uint = new UIntTypeMapping("integer", DbType.UInt32); private readonly LongTypeMapping _bigint = new LongTypeMapping("bigint", DbType.Int64); private readonly ULongTypeMapping _ubigint = new ULongTypeMapping("bigint", DbType.UInt64); // decimals private readonly DecimalTypeMapping _decimal = new DecimalTypeMapping("decimal(18,4)", DbType.Decimal); private readonly DoubleTypeMapping _double = new DoubleTypeMapping("DOUBLE PRECISION", DbType.Double); private readonly FloatTypeMapping _float = new FloatTypeMapping("float"); // binary private readonly RelationalTypeMapping _binary = new FbByteArrayTypeMapping("BLOB SUB_TYPE 0 SEGMENT SIZE 80", DbType.Binary); private readonly RelationalTypeMapping _varbinary = new FbByteArrayTypeMapping("BLOB SUB_TYPE 0 SEGMENT SIZE 80", DbType.Binary); private readonly FbByteArrayTypeMapping _varbinary767 = new FbByteArrayTypeMapping("BLOB SUB_TYPE 0 SEGMENT SIZE 80", DbType.Binary, 767); private readonly RelationalTypeMapping _varbinarymax = new FbByteArrayTypeMapping("BLOB SUB_TYPE 0 SEGMENT SIZE 80", DbType.Binary); // string private readonly FbStringTypeMapping _char = new FbStringTypeMapping("char", DbType.AnsiStringFixedLength); private readonly FbStringTypeMapping _varchar = new FbStringTypeMapping("varchar", DbType.AnsiString); private readonly FbStringTypeMapping _varchar127 = new FbStringTypeMapping("varchar(127)", DbType.AnsiString, true, 127); private readonly FbStringTypeMapping _varcharmax = new FbStringTypeMapping("varchar(4000)", DbType.AnsiString); // DateTime private readonly FbDateTimeTypeMapping _timeStamp = new FbDateTimeTypeMapping("TIMESTAMP", DbType.DateTime); private readonly TimeSpanTypeMapping _time = new TimeSpanTypeMapping("time", DbType.Time); // json private readonly RelationalTypeMapping _json = new FbStringTypeMapping("BLOB SUB_TYPE 1 SEGMENT SIZE 80", DbType.AnsiString); // row version private readonly RelationalTypeMapping _rowversion = new FbDateTimeTypeMapping("TIMESTAMP", DbType.DateTime); // guid private readonly GuidTypeMapping _uniqueidentifier = new GuidTypeMapping("varchar(38)", DbType.Guid); readonly Dictionary<string, RelationalTypeMapping> _storeTypeMappings; readonly Dictionary<Type, RelationalTypeMapping> _clrTypeMappings; private readonly HashSet<string> _disallowedMappings; public FbTypeMapper([NotNull] RelationalTypeMapperDependencies dependencies) : base(dependencies) { _storeTypeMappings = new Dictionary<string, RelationalTypeMapping>(StringComparer.OrdinalIgnoreCase) { // TODO // boolean { "bit", _bit }, // integers // { "tinyint", _tinyint }, // { "tinyint unsigned", _utinyint }, { "smallint", _smallint }, // { "smallint unsigned", _usmallint }, // { "mediumint", _int }, // { "mediumint unsigned", _uint }, { "integer", _int }, // { "int unsigned", _uint }, { "bigint", _bigint }, //{ "bigint unsigned", _ubigint }, // decimals { "DECIMAL", _decimal }, { "DOUBLE PRECISION", _double }, { "FLOAT", _float }, // TODO // binary { "BLOB SUB_TYPE 0", _binary }, //{ "varbinary", _varbinary }, //{ "tinyblob", _varbinarymax }, // { "blob", _varbinarymax }, // { "mediumblob", _varbinarymax }, // { "longblob", _varbinarymax }, // string { "char", _char }, { "varchar", _varchar }, // TODO { "BLOB SUB_TYPE 1", _json }, // { "text", _varcharmax }, // { "mediumtext", _varcharmax }, // { "varchar(4000)", _varcharmax }, // DateTime { "date", _timeStamp }, { "time", _time }, { "timestamp", _timeStamp }, // json // { "json", _json }, // guid { "char(38)", _uniqueidentifier } }; _clrTypeMappings = new Dictionary<Type, RelationalTypeMapping> { // boolean { typeof(bool), _bit }, // integers { typeof(short), _smallint }, { typeof(ushort), _usmallint }, { typeof(int), _int }, { typeof(uint), _uint }, { typeof(long), _bigint }, { typeof(ulong), _ubigint }, // decimals { typeof(decimal), _decimal }, { typeof(float), _float }, { typeof(double), _double }, // byte / char { typeof(sbyte), _tinyint }, { typeof(byte), _utinyint }, { typeof(char), _utinyint }, // DateTime { typeof(DateTime), _timeStamp }, { typeof(DateTimeOffset), _timeStamp }, { typeof(TimeSpan), _time }, // json { typeof(JsonObject<>), _json }, // guid { typeof(Guid), _uniqueidentifier } }; _disallowedMappings = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "binary", "char", "varbinary", "varchar" }; ByteArrayMapper // TODO = new ByteArrayRelationalTypeMapper( 8000, _varbinarymax, _varbinarymax, _varbinary767, _rowversion, size => new FbByteArrayTypeMapping("BLOB SUB_TYPE 0 SEGMENT SIZE 80", DbType.Binary)); StringMapper = new StringRelationalTypeMapper( maxBoundedAnsiLength: 4000, defaultAnsiMapping: _varcharmax, unboundedAnsiMapping: _varcharmax, keyAnsiMapping: _varchar127, createBoundedAnsiMapping: size => new FbStringTypeMapping( "varchar(" + size + ")", DbType.AnsiString, unicode: false, size: size), maxBoundedUnicodeLength: 4000, defaultUnicodeMapping: _varcharmax, unboundedUnicodeMapping: _varcharmax, keyUnicodeMapping: _varchar127, createBoundedUnicodeMapping: size => new FbStringTypeMapping( "varchar(" + size + ")", DbType.AnsiString, unicode: false, size: size)); } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override IByteArrayRelationalTypeMapper ByteArrayMapper { get; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override IStringRelationalTypeMapper StringMapper { get; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override void ValidateTypeName(string storeType) { if (_disallowedMappings.Contains(storeType)) { throw new ArgumentException("UnqualifiedDataType" + storeType); } } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override string GetColumnType(IProperty property) => property.Firebird().ColumnType; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override IReadOnlyDictionary<Type, RelationalTypeMapping> GetClrTypeMappings() => _clrTypeMappings; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override IReadOnlyDictionary<string, RelationalTypeMapping> GetStoreTypeMappings() => _storeTypeMappings; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override RelationalTypeMapping FindMapping(Type clrType) { Check.NotNull(clrType, nameof(clrType)); clrType = clrType.UnwrapNullableType().UnwrapEnumType(); if (clrType.Name == typeof(JsonObject<>).Name) return _json; return clrType == typeof(string) ? _varcharmax : (clrType == typeof(byte[]) ? _varbinarymax : base.FindMapping(clrType)); } // Indexes in SQL Server have a max size of 900 bytes /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override bool RequiresKeyMapping(IProperty property) => base.RequiresKeyMapping(property) || property.IsIndex(); } }
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using EasyNetQ; using EasyNetQ.Topology; using Microsoft.Extensions.Logging; using NetFusion.Bootstrap.Exceptions; using NetFusion.Bootstrap.Plugins; using NetFusion.Common.Extensions.Collections; using NetFusion.RabbitMQ.Metadata; using NetFusion.RabbitMQ.Publisher; using NetFusion.RabbitMQ.Publisher.Internal; namespace NetFusion.RabbitMQ.Plugin.Modules { /// <summary> /// Plugin module encapsulating the concerns of the publisher. Finds all exchange definitions /// describing the exchanges/queues to which messages can be sent. This discovered metadata /// is then used to create the needed exchanges and queues by delegating to the EasyNetQ /// advanced API. /// </summary> public class PublisherModule : PluginModule, IPublisherModule { // Dependent Modules: protected IBusModule BusModule { get; set; } // Other plugins (normally application plugins) specify the exchanges // to be created by defining one or more IExchangeRegistry derived types. public IEnumerable<IExchangeRegistry> Registries { get; protected set; } // Records, for a given message type, the exchange metadata and the exchange // created from the metadata to which the message should be published. private IDictionary<Type, ExchangeMeta> _messageExchanges; private readonly IDictionary<Type, CreatedExchange> _createdExchanges; // Stores for the unique set of named RPC exchanges the associated RPC client that will create a queue, // on the default exchange, to process replies from the consumer containing the response to the original // sent command. A client and replay queue is created for each unique RPC exchange name allowing a single // queue to process replies from various RPC commands. It also allows the application to group common // commands based on concern or processing distribution needs. private readonly IDictionary<string, IRpcClient> _exchangeRpcClients; public PublisherModule() { _createdExchanges = new Dictionary<Type, CreatedExchange>(); _exchangeRpcClients = new Dictionary<string, IRpcClient>(); } //----------- [Plugin Initialization] --------------- public override void Configure() { var definitions = Registries.SelectMany(r => r.GetDefinitions()).ToArray(); ApplyConfiguredOverrides(definitions); AssertExchangeDefinitions(definitions); _messageExchanges = definitions.ToDictionary(m => m.MessageType); } // All exchange types: Direct, Topic, and Fan-out are defined within code with the most common default // values. These default values can be overridden by specifying them within the application's configuration. private void ApplyConfiguredOverrides(IEnumerable<ExchangeMeta> definitions) { foreach (ExchangeMeta definition in definitions) { BusModule.ApplyExchangeSettings(definition); } } private static void AssertExchangeDefinitions(ExchangeMeta[] definitions) { AssertNoDuplicateExchanges(definitions); AssertNoDuplicateQueues(definitions); AssertNoDuplicateMessageTypes(definitions); } private static void AssertNoDuplicateExchanges(ExchangeMeta[] definitions) { // All exchange names that are not RPC exchanges must be unique for given named bus. // Default exchanges are excluded since they don't have names. var duplicateExchangeNames = definitions.Where( d => !d.IsDefaultExchange && !d.IsRpcExchange) .WhereDuplicated(d => new { d.BusName, d.ExchangeName}); if (duplicateExchangeNames.Any()) { throw new ContainerException( "Exchange names must be unique for a given named bus. The following have been configured " + "more than once.", "duplicate-exchanges", duplicateExchangeNames); } // Validate that all RPC exchanges are unique by bus, queue, and action namespace. var duplicateRpcExchanges = definitions.Where(d => d.IsRpcExchange) .WhereDuplicated(d => new { d.BusName, d.QueueMeta.QueueName, d.ActionNamespace}); if (duplicateRpcExchanges.Any()) { throw new ContainerException( "For RPC exchanges names must be unique for a given named bus, queue, and action namespace. " + "The following have been configured more than once.", "duplicate-queues", duplicateRpcExchanges); } } private static void AssertNoDuplicateQueues(IEnumerable<ExchangeMeta> definitions) { var duplicateQueueNames = definitions.Where(d => d.IsDefaultExchange && !d.IsRpcExchange) .WhereDuplicated(d => new { d.BusName, d.QueueMeta.QueueName }); if (duplicateQueueNames.Any()) { throw new ContainerException( "Queue names, defined on the default exchange, must be unique for a given named bus. " + "The following have been configured more than once.", "duplicate-queues", duplicateQueueNames); } } private static void AssertNoDuplicateMessageTypes(IEnumerable<ExchangeMeta> definitions) { var duplicateMessages = definitions.GroupBy(d => d.MessageType) .Where(g => g.Count() > 1) .Select(g => new { MessageType = g.Key, Definitions = g.Select(d => $"Exchange: {d.ExchangeName}, Queue: {d.QueueMeta?.QueueName}") }).ToArray(); if (duplicateMessages.Any()) { throw new ContainerException( "Message type can only be associated with one exchange or queue.", "duplicate-message-types", duplicateMessages); } } //----------- [Plugin Execution] --------------- protected override async Task OnStartModuleAsync(IServiceProvider services) { await CreateExchanges(_messageExchanges.Values); await CreateRpcExchangeClients(_messageExchanges.Values); BusModule.Reconnection += async (sender, args) => await HandleReconnection(args); } protected override Task OnStopModuleAsync(IServiceProvider services) { foreach(IRpcClient client in _exchangeRpcClients.Values) { client.Dispose(); } return base.OnStopModuleAsync(services); } private async Task CreateExchanges(IEnumerable<ExchangeMeta> definitions) { foreach (ExchangeMeta exchangeMeta in definitions) { IBus bus = BusModule.GetBus(exchangeMeta.BusName); IExchange exchange = await bus.Advanced.ExchangeDeclareAsync(exchangeMeta); var createdExchange = new CreatedExchange(bus, exchange, exchangeMeta); _createdExchanges[exchangeMeta.MessageType] = createdExchange; } } // Creates a RPC client for each RPC exchange. RPC style commands are passed through // this client when sent. It also monitors the reply queue for commands responses // that are correlated back to the original sent command. private async Task CreateRpcExchangeClients(IEnumerable<ExchangeMeta> definitions) { var rpcExchanges = definitions.Where(d => d.IsRpcExchange); foreach (ExchangeMeta rpcExchange in rpcExchanges) { string rpcClientKey = $"{rpcExchange.BusName}|{rpcExchange.QueueMeta.QueueName}"; if (! _exchangeRpcClients.ContainsKey(rpcClientKey)) { var rpcClient = CreateRpcClient(rpcExchange); _exchangeRpcClients[rpcClientKey] = rpcClient; await rpcClient.CreateAndSubscribeToReplyQueueAsync(); } } } protected virtual IRpcClient CreateRpcClient(ExchangeMeta definition) { IBus bus = BusModule.GetBus(definition.BusName); var rpcClient = new RpcClient(definition.BusName, definition.QueueMeta.QueueName, bus); var logger = Context.LoggerFactory.CreateLogger<RpcClient>(); rpcClient.SetLogger(logger); return rpcClient; } // Called when a reconnection to the the broker is detected. The IBus will reestablish // the connection when available. However, the reconnection could mean that the broker // was restarted. In this case, any auto-delete queues will need to be recreated. private async Task HandleReconnection(ReconnectionEventArgs eventArgs) { // Recreate all exchanges/queues on the bus for which the connection was restored. // RabbitMQ will only create these entities if they are not already present. var busExchanges = _messageExchanges.Values .Where(e => e.BusName == eventArgs.Connection.BusName) .ToArray(); await CreateExchanges(busExchanges); // Next, recreate all IRpcClient reply-queues that belong to bus // that was reconnected. var busRpcClients = _exchangeRpcClients.Values .Where(c => c.BusName == eventArgs.Connection.BusName) .ToArray(); foreach (IRpcClient client in busRpcClients) { await client.CreateAndSubscribeToReplyQueueAsync(); } } //----------- [Plugin Services] --------------- // Determines if the specified message should be delivered to an exchange. public bool IsExchangeMessage(Type messageType) { if (messageType == null) throw new ArgumentNullException(nameof(messageType)); return _messageExchanges.ContainsKey(messageType); } // Returns information about the exchange to which a given type of message should be delivered. public ExchangeMeta GetExchangeMeta(Type messageType) { if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (! IsExchangeMessage(messageType)) { throw new InvalidOperationException( $"No exchange definition registered for message type: {messageType}"); } return _messageExchanges[messageType]; } // Returns exchange to which a given type of message should be delivered. public CreatedExchange GetExchange(Type messageType) { if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (! IsExchangeMessage(messageType)) { throw new InvalidOperationException( $"No exchange definition registered for message type: {messageType}"); } return _createdExchanges[messageType]; } // Returns the RPC Client used to deliver a message to a consumer for which a response // will be received on a corresponding queue and returned to the sender of the command. public IRpcClient GetRpcClient(string busName, string queueName) { if (string.IsNullOrWhiteSpace(busName)) throw new ArgumentException("Bus not specified.", nameof(busName)); if (string.IsNullOrWhiteSpace(queueName)) throw new ArgumentException("Queue not not specified.", nameof(queueName)); string rpcClientKey = $"{busName}|{queueName}"; if (! _exchangeRpcClients.TryGetValue(rpcClientKey, out IRpcClient client)) { throw new InvalidOperationException( $"RPC client for the queue named: {queueName} on bus: {busName} is not registered."); } return client; } //----------- [Plugin Logging] --------------- public override void Log(IDictionary<string, object> moduleLog) { moduleLog["PublisherExchanges"] = _messageExchanges.Values.Select(e => { var exchangeLog = new Dictionary<string, object>(); e.LogProperties(exchangeLog); return exchangeLog; }).ToArray(); } } }
//------------------------------------------------------------------------------ // <copyright file="DebugReflectPropertyDescriptor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #if DEBUG /* This class exists in debug only. It is a complete copy of the V1.0 TypeDescriptor object and is used to validate that the behavior of the V2.0 TypeDescriptor matches 1.0 behavior. */ namespace System.ComponentModel { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using Microsoft.Win32; using System.Security; using System.Security.Permissions; using System.ComponentModel.Design; using System.ComponentModel; /// <internalonly/> /// <devdoc> /// <para> /// DebugReflectPropertyDescriptor defines a property. Properties are the main way that a user can /// set up the state of a component. /// The DebugReflectPropertyDescriptor class takes a component class that the property lives on, /// a property name, the type of the property, and various attributes for the /// property. /// For a property named XXX of type YYY, the associated component class is /// required to implement two methods of the following /// form: /// </para> /// <code> /// public YYY GetXXX(); /// public void SetXXX(YYY value); /// </code> /// The component class can optionally implement two additional methods of /// the following form: /// <code> /// public boolean ShouldSerializeXXX(); /// public void ResetXXX(); /// </code> /// These methods deal with a property's default value. The ShouldSerializeXXX() /// method returns true if the current value of the XXX property is different /// than it's default value, so that it should be persisted out. The ResetXXX() /// method resets the XXX property to its default value. If the DebugReflectPropertyDescriptor /// includes the default value of the property (using the DefaultValueAttribute), /// the ShouldSerializeXXX() and ResetXXX() methods are ignored. /// If the DebugReflectPropertyDescriptor includes a reference to an editor /// then that value editor will be used to /// edit the property. Otherwise, a system-provided editor will be used. /// Various attributes can be passed to the DebugReflectPropertyDescriptor, as are described in /// Attribute. /// ReflectPropertyDescriptors can be obtained by a user programmatically through the /// ComponentManager. /// </devdoc> [HostProtection(SharedState = true)] internal sealed class DebugReflectPropertyDescriptor : PropertyDescriptor { private static readonly Type[] argsNone = new Type[0]; private static readonly object noValue = new object(); private static TraceSwitch PropDescCreateSwitch = new TraceSwitch("PropDescCreate", "DebugReflectPropertyDescriptor: Dump errors when creating property info"); private static TraceSwitch PropDescUsageSwitch = new TraceSwitch("PropDescUsage", "DebugReflectPropertyDescriptor: Debug propertydescriptor usage"); private static TraceSwitch PropDescSwitch = new TraceSwitch("PropDesc", "DebugReflectPropertyDescriptor: Debug property descriptor"); private static readonly int BitDefaultValueQueried = BitVector32.CreateMask(); private static readonly int BitGetQueried = BitVector32.CreateMask(BitDefaultValueQueried); private static readonly int BitSetQueried = BitVector32.CreateMask(BitGetQueried); private static readonly int BitShouldSerializeQueried = BitVector32.CreateMask(BitSetQueried); private static readonly int BitResetQueried = BitVector32.CreateMask(BitShouldSerializeQueried); private static readonly int BitChangedQueried = BitVector32.CreateMask(BitResetQueried); private static readonly int BitReadOnlyChecked = BitVector32.CreateMask(BitChangedQueried); private static readonly int BitAmbientValueQueried = BitVector32.CreateMask(BitReadOnlyChecked); internal BitVector32 state = new BitVector32(); // Contains the state bits for this proeprty descriptor. Type componentClass; // used to determine if we should all on us or on the designer Type type; // the data type of the property internal object defaultValue; // the default value of the property (or noValue) internal object ambientValue; // the ambient value of the property (or noValue) internal PropertyInfo propInfo; // the property info internal MethodInfo getMethod; // the property get method internal MethodInfo setMethod; // the property set method internal MethodInfo shouldSerializeMethod; // the should serialize method internal MethodInfo resetMethod; // the reset property method EventInfo realChangedEventInfo; // Changed event handler on object Type receiverType; // Only set if we are an extender private TypeConverter converter; private object[] editors; private Type[] editorTypes; private int editorCount; /// <devdoc> /// The main constructor for ReflectPropertyDescriptors. /// </devdoc> public DebugReflectPropertyDescriptor(Type componentClass, string name, Type type, Attribute[] attributes) : base(name, attributes) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "Creating DebugReflectPropertyDescriptor for " + componentClass.FullName + "." + name); try { if (type == null) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "type == null, name == " + name); throw new ArgumentException(SR.GetString(SR.ErrorInvalidPropertyType, name)); } if (componentClass == null) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "componentClass == null, name == " + name); throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass")); } this.type = type; this.componentClass = componentClass; } catch (Exception t) { Debug.Fail("Property '" + name + "' on component " + componentClass.FullName + " failed to init."); Debug.Fail(t.ToString()); throw t; } } /// <devdoc> /// A constructor for ReflectPropertyDescriptors that have no attributes. /// </devdoc> public DebugReflectPropertyDescriptor(Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { this.propInfo = propInfo; this.getMethod = getMethod; this.setMethod = setMethod; state[BitGetQueried | BitSetQueried] = true; } /// <devdoc> /// A constructor for ReflectPropertyDescriptors that creates an extender property. /// </devdoc> public DebugReflectPropertyDescriptor(Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { this.receiverType = receiverType; this.getMethod = getMethod; this.setMethod = setMethod; state[BitGetQueried | BitSetQueried] = true; } /// <devdoc> /// This constructor takes an existing DebugReflectPropertyDescriptor and modifies it by merging in the /// passed-in attributes. /// </devdoc> public DebugReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes) : base(oldReflectPropertyDescriptor, attributes) { this.componentClass = componentClass; this.type = oldReflectPropertyDescriptor.PropertyType; if (componentClass == null) { throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass")); } // If the classes are the same, we can potentially optimize the method fetch because // the old property descriptor may already have it. // if (oldReflectPropertyDescriptor is DebugReflectPropertyDescriptor) { DebugReflectPropertyDescriptor oldProp = (DebugReflectPropertyDescriptor)oldReflectPropertyDescriptor; if (oldProp.ComponentType == componentClass) { propInfo = oldProp.propInfo; getMethod = oldProp.getMethod; setMethod = oldProp.setMethod; shouldSerializeMethod = oldProp.shouldSerializeMethod; resetMethod = oldProp.resetMethod; defaultValue = oldProp.defaultValue; ambientValue = oldProp.ambientValue; state = oldProp.state; } // Now we must figure out what to do with our default value. First, check to see // if the caller has provided an new default value attribute. If so, use it. Otherwise, // just let it be and it will be picked up on demand. // if (attributes != null) { foreach(Attribute a in attributes) { if (a is DefaultValueAttribute) { defaultValue = ((DefaultValueAttribute)a).Value; state[BitDefaultValueQueried] = true; } else if (a is AmbientValueAttribute) { ambientValue = ((AmbientValueAttribute)a).Value; state[BitAmbientValueQueried] = true; } } } } } /// <devdoc> /// Retrieves the ambient value for this property. /// </devdoc> private object AmbientValue { get { if (!state[BitAmbientValueQueried]) { state[BitAmbientValueQueried] = true; Attribute a = Attributes[typeof(AmbientValueAttribute)]; if (a != null) { ambientValue = ((AmbientValueAttribute)a).Value; } else { ambientValue = noValue; } } return ambientValue; } } /// <devdoc> /// The EventInfo for the changed event on the component, or null if there isn't one for this property. /// </devdoc> private EventInfo ChangedEventValue { get { if (!state[BitChangedQueried]) { state[BitChangedQueried] = true; realChangedEventInfo = ComponentType.GetEvent(Name + "Changed", BindingFlags.Public | BindingFlags.Instance); } return realChangedEventInfo; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { realChangedEventInfo = value; state[BitChangedQueried] = true; } */ } /// <devdoc> /// Retrieves the type of the component this PropertyDescriptor is bound to. /// </devdoc> public override Type ComponentType { get { return componentClass; } } /// <devdoc> /// <para> /// Gets the type converter for this property. /// </para> /// </devdoc> public override TypeConverter Converter { get { if (converter == null) { TypeConverterAttribute attr = (TypeConverterAttribute)Attributes[typeof(TypeConverterAttribute)]; if (attr.ConverterTypeName != null && attr.ConverterTypeName.Length > 0) { Type converterType = GetTypeFromName(attr.ConverterTypeName); if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) { converter = (TypeConverter)CreateInstance(converterType); } } if (converter == null) { converter = DebugTypeDescriptor.GetConverter(PropertyType); } } return converter; } } /// <devdoc> /// Retrieves the default value for this property. /// </devdoc> private object DefaultValue { get { if (!state[BitDefaultValueQueried]) { state[BitDefaultValueQueried] = true; Attribute a = Attributes[typeof(DefaultValueAttribute)]; if (a != null) { defaultValue = ((DefaultValueAttribute)a).Value; } else { defaultValue = noValue; } } return defaultValue; } } /// <devdoc> /// The GetMethod for this property /// </devdoc> private MethodInfo GetMethodValue { get { if (!state[BitGetQueried]) { state[BitGetQueried] = true; if (receiverType == null) { if (propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } if (propInfo != null) { getMethod = propInfo.GetGetMethod(true); } if (getMethod == null) { throw new InvalidOperationException(SR.GetString(SR.ErrorMissingPropertyAccessors, componentClass.FullName + "." + Name)); } } else { getMethod = FindMethod(componentClass, "Get" + Name, new Type[] {receiverType}, type); if (getMethod == null) { throw new ArgumentException(SR.GetString(SR.ErrorMissingPropertyAccessors, Name)); } } } return getMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitGetQueried] = true; getMethod = value; } */ } /// <devdoc> /// Determines if this property is an extender property. /// </devdoc> private bool IsExtender { get { return (receiverType != null); } } /// <devdoc> /// Indicates whether this property is read only. /// </devdoc> public override bool IsReadOnly { get { return SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; } } /// <devdoc> /// Retrieves the type of the property. /// </devdoc> public override Type PropertyType { get { return type; } } /// <devdoc> /// Access to the reset method, if one exists for this property. /// </devdoc> private MethodInfo ResetMethodValue { get { if (!state[BitResetQueried]) { state[BitResetQueried] = true; Type[] args; if (receiverType == null) { args = argsNone; } else { args = new Type[] {receiverType}; } #if !DISABLE_CAS_USE IntSecurity.FullReflection.Assert(); #endif try { resetMethod = FindMethod(componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false); } finally { CodeAccessPermission.RevertAssert(); } } return resetMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitResetQueried] = true; resetMethod = value; } */ } /// <devdoc> /// Accessor for the set method /// </devdoc> private MethodInfo SetMethodValue { get { if (!state[BitSetQueried]) { state[BitSetQueried] = true; if (receiverType == null) { if (propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } if (propInfo != null) { setMethod = propInfo.GetSetMethod(true); } } else { setMethod = FindMethod(componentClass, "Set" + Name, new Type[] { receiverType, type}, typeof(void)); } } return setMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitSetQueried] = true; setMethod = value; } */ } /// <devdoc> /// Accessor for the ShouldSerialize method. /// </devdoc> private MethodInfo ShouldSerializeMethodValue { get { if (!state[BitShouldSerializeQueried]) { state[BitShouldSerializeQueried] = true; Type[] args; if (receiverType == null) { args = argsNone; } else { args = new Type[] {receiverType}; } #if !DISABLE_CAS_USE IntSecurity.FullReflection.Assert(); #endif try { shouldSerializeMethod = FindMethod(componentClass, "ShouldSerialize" + Name, args, typeof(Boolean), /* publicOnly= */ false); } finally { CodeAccessPermission.RevertAssert(); } } return shouldSerializeMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitShouldSerializeQueried] = true; shouldSerializeMethod = value; } */ } /// <devdoc> /// Allows interested objects to be notified when this property changes. /// </devdoc> public override void AddValueChanged(object component, EventHandler handler) { if (component == null) throw new ArgumentNullException("component"); if (handler == null) throw new ArgumentNullException("handler"); EventInfo changedEvent = ChangedEventValue; if (changedEvent != null) { changedEvent.AddEventHandler(component, handler); } else { base.AddValueChanged(component, handler); } } internal bool ExtenderCanResetValue(IExtenderProvider provider, object component) { if (DefaultValue != noValue) { return !object.Equals(ExtenderGetValue(provider, component),defaultValue); } MethodInfo reset = ResetMethodValue; if (reset != null) { MethodInfo shouldSerialize = ShouldSerializeMethodValue; if (shouldSerialize != null) { try { provider = (IExtenderProvider)GetDebugInvokee(componentClass, provider); return (bool)shouldSerialize.Invoke(provider, new object[] { component}); } catch {} } } else { return true; } return false; } internal Type ExtenderGetReceiverType() { return receiverType; } internal Type ExtenderGetType(IExtenderProvider provider) { return PropertyType; } internal object ExtenderGetValue(IExtenderProvider provider, object component) { if (provider != null) { provider = (IExtenderProvider)GetDebugInvokee(componentClass, provider); return GetMethodValue.Invoke(provider, new object[] { component}); } return null; } internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc) { if (DefaultValue != noValue) { ExtenderSetValue(provider, component, DefaultValue, notifyDesc); } else if (AmbientValue != noValue) { ExtenderSetValue(provider, component, AmbientValue, notifyDesc); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } provider = (IExtenderProvider)GetDebugInvokee(componentClass, provider); if (ResetMethodValue != null) { ResetMethodValue.Invoke(provider, new object[] { component}); // Now notify the change service that the change was successful. // if (changeService != null) { newValue = ExtenderGetValue(provider, component); changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue); } } } } internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc) { if (provider != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } provider = (IExtenderProvider)GetDebugInvokee(componentClass, provider); if (SetMethodValue != null) { SetMethodValue.Invoke(provider, new object[] { component, value}); // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, notifyDesc, oldValue, value); } } } } internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component) { provider = (IExtenderProvider)GetDebugInvokee(componentClass, provider); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component}); } catch {} } return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); } else if (DefaultValue == noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component}); } catch {} } return true; } return !object.Equals(DefaultValue, ExtenderGetValue(provider, component)); } /// <devdoc> /// Indicates whether reset will change the value of the component. If there /// is a DefaultValueAttribute, then this will return true if getValue returns /// something different than the default value. If there is a reset method and /// a ShouldSerialize method, this will return what ShouldSerialize returns. /// If there is just a reset method, this always returns true. If none of these /// cases apply, this returns false. /// </devdoc> public override bool CanResetValue(object component) { if (IsExtender) { return false; } if (DefaultValue != noValue) { return !object.Equals(GetValue(component),DefaultValue); } if (ResetMethodValue != null) { if (ShouldSerializeMethodValue != null) { component = GetDebugInvokee(componentClass, component); try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return true; } if (AmbientValue != noValue) { return ShouldSerializeValue(component); } return false; } protected override void FillAttributes(IList attributes) { Debug.Assert(componentClass != null, "Must have a component class for FillAttributes"); // // The order that we fill in attributes is critical. The list of attributes will be // filtered so that matching attributes at the end of the list replace earlier matches // (last one in wins). Therefore, the three categories of attributes we add must be // added as follows: // // 1. Attributes of the property type. These are the lowest level and should be // overwritten by any newer attributes. // // 2. Attributes of the property itself, from base class to most derived. This way // derived class attributes replace base class attributes. // // 3. Attributes from our base MemberDescriptor. While this seems opposite of what // we want, MemberDescriptor only has attributes if someone passed in a new // set in the constructor. Therefore, these attributes always // supercede existing values. // // We need to include attributes from the type of the property. // foreach (Attribute typeAttr in DebugTypeDescriptor.GetAttributes(PropertyType)) { attributes.Add(typeAttr); } // NOTE : Must look at method OR property, to handle the case of Extender properties... // // Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-aquire // : the property info, rather than use the one we have cached. The one we have cached // : may ave come from a base class, meaning we will request custom metadata for this // : class twice. BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly; Type currentReflectType = componentClass; int depth = 0; // First, calculate the depth of the object hierarchy. We do this so we can do a single // object create for an array of attributes. // while(currentReflectType != null && currentReflectType != typeof(object)) { depth++; currentReflectType = currentReflectType.BaseType; } // Now build up an array in reverse order // if (depth > 0) { currentReflectType = componentClass; object[][] attributeStack = new object[depth][]; while(currentReflectType != null && currentReflectType != typeof(object)) { MemberInfo memberInfo = null; // Fill in our member info so we can get at the custom attributes. // if (IsExtender) { memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags); } else { memberInfo = currentReflectType.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } // Get custom attributes for the member info. // if (memberInfo != null) { attributeStack[--depth] = DebugTypeDescriptor.GetCustomAttributes(memberInfo); } // Ready for the next loop iteration. // currentReflectType = currentReflectType.BaseType; } // Now trawl the attribute stack so that we add attributes // from base class to most derived. // foreach(object[] attributeArray in attributeStack) { if (attributeArray != null) { foreach(object attr in attributeArray) { if (attr is Attribute) { attributes.Add(attr); } } } } } // Include the base attributes. These override all attributes on the actual // property, so we want to add them last. // base.FillAttributes(attributes); // Finally, override any form of ReadOnlyAttribute. // if (!state[BitReadOnlyChecked]) { state[BitReadOnlyChecked] = true; if (SetMethodValue == null) { attributes.Add(ReadOnlyAttribute.Yes); } } } /// <devdoc> /// Retrieves the properties /// </devdoc> public override PropertyDescriptorCollection GetChildProperties(object instance, Attribute[] filter) { if (instance == null) { return DebugTypeDescriptor.GetProperties(PropertyType, filter); } else { return DebugTypeDescriptor.GetProperties(instance, filter); } } /// <devdoc> /// <para> /// Gets /// the component /// that a method should be invoked on. /// </para> /// </devdoc> private static object GetDebugInvokee(Type componentClass, object component) { // We delve into the component's designer only if it is a component and if // the component we've been handed is not an instance of this property type. // if (!componentClass.IsInstanceOfType(component) && component is IComponent) { ISite site = ((IComponent)component).Site; if (site != null && site.DesignMode) { IDesignerHost host = (IDesignerHost)site.GetService(typeof(IDesignerHost)); if (host != null) { object designer = host.GetDesigner((IComponent)component); // We only use the designer if it has a compatible class. If we // got here, we're probably hosed because the user just passed in // an object that this PropertyDescriptor can't munch on, but it's // clearer to use that object instance instead of it's designer. // if (designer != null && componentClass.IsInstanceOfType(designer)) { component = designer; } } } } Debug.Assert(component != null, "Attempt to invoke on null component"); return component; } /// <devdoc> /// <para> /// Gets an editor of the specified type. /// </para> /// </devdoc> public override object GetEditor(Type editorBaseType) { object editor = null; // Check the editors we've already created for this type. // if (editorTypes != null) { for (int i = 0; i < editorCount; i++) { if (editorTypes[i] == editorBaseType) { return editors[i]; } } } // If one wasn't found, then we must go through the attributes. // if (editor == null) { for (int i = 0; i < Attributes.Count; i++) { if (!(Attributes[i] is EditorAttribute)) { continue; } EditorAttribute attr = (EditorAttribute)Attributes[i]; Type editorType = GetTypeFromName(attr.EditorBaseTypeName); if (editorBaseType == editorType) { Type type = GetTypeFromName(attr.EditorTypeName); if (type != null) { editor = CreateInstance(type); break; } } } // Now, if we failed to find it in our own attributes, go to the // component descriptor. // if (editor == null) { editor = DebugTypeDescriptor.GetEditor(PropertyType, editorBaseType); } // Now, another slot in our editor cache for next time // if (editorTypes == null) { editorTypes = new Type[5]; editors = new object[5]; } if (editorCount >= editorTypes.Length) { Type[] newTypes = new Type[editorTypes.Length * 2]; object[] newEditors = new object[editors.Length * 2]; Array.Copy(editorTypes, newTypes, editorTypes.Length); Array.Copy(editors, newEditors, editors.Length); editorTypes = newTypes; editors = newEditors; } editorTypes[editorCount] = editorBaseType; editors[editorCount++] = editor; } return editor; } /// <devdoc> /// Retrieves the current value of the property on component, /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// </devdoc> public override object GetValue(object component) { #if DEBUG if (PropDescUsageSwitch.TraceVerbose) { string compName = "(null)"; if (component != null) compName = component.ToString(); Debug.WriteLine("[" + Name + "]: GetValue(" + compName + ")"); } #endif if (IsExtender) { Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null"); return null; } Debug.Assert(component != null, "GetValue must be given a component"); if (component != null) { component = GetDebugInvokee(componentClass, component); try { return GetMethodValue.Invoke(component, null); } catch (Exception t) { string name = null; if (component is IComponent) { ISite site = ((IComponent)component).Site; if (site != null && site.Name != null) { name = site.Name; } } if (name == null) { name = component.GetType().FullName; } if (t is TargetInvocationException) { t = t.InnerException; } string message = t.Message; if (message == null) { message = t.GetType().Name; } throw new TargetInvocationException(SR.GetString(SR.ErrorPropertyAccessorException, Name, name, message), t); } } Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null"); return null; } /// <devdoc> /// This should be called by your property descriptor implementation /// when the property value has changed. /// </devdoc> protected override void OnValueChanged(object component, EventArgs e) { if (state[BitChangedQueried] && realChangedEventInfo == null) { base.OnValueChanged(component, e); } } /// <devdoc> /// Allows interested objects to be notified when this property changes. /// </devdoc> public override void RemoveValueChanged(object component, EventHandler handler) { if (component == null) throw new ArgumentNullException("component"); if (handler == null) throw new ArgumentNullException("handler"); EventInfo changedEvent = ChangedEventValue; if (changedEvent != null) { changedEvent.RemoveEventHandler(component, handler); } else { base.RemoveValueChanged(component, handler); } } /// <devdoc> /// Will reset the default value for this property on the component. If /// there was a default value passed in as a DefaultValueAttribute, that /// value will be set as the value of the property on the component. If /// there was no default value passed in, a ResetXXX method will be looked /// for. If one is found, it will be invoked. If one is not found, this /// is a nop. /// </devdoc> public override void ResetValue(object component) { object invokee = GetDebugInvokee(componentClass, component); if (DefaultValue != noValue) { SetValue(component, DefaultValue); } else if (AmbientValue != noValue) { SetValue(component, AmbientValue); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = GetMethodValue.Invoke(invokee, (object[])null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } catch { throw; } } if (ResetMethodValue != null) { ResetMethodValue.Invoke(invokee, (object[])null); // Now notify the change service that the change was successful. // if (changeService != null) { newValue = GetMethodValue.Invoke(invokee, (object[])null); changeService.OnComponentChanged(component, this, oldValue, newValue); } } } } /// <devdoc> /// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// </devdoc> public override void SetValue(object component, object value) { #if DEBUG if (PropDescUsageSwitch.TraceVerbose) { string compName = "(null)"; string valName = "(null)"; if (component != null) compName = component.ToString(); if (value != null) valName = value.ToString(); Debug.WriteLine("[" + Name + "]: SetValue(" + compName + ", " + valName + ")"); } #endif if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object invokee = GetDebugInvokee(componentClass, component); Debug.Assert(!IsReadOnly, "SetValue attempted on read-only property [" + Name + "]"); if (!IsReadOnly) { // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = GetMethodValue.Invoke(invokee, null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } try { try { SetMethodValue.Invoke(invokee, new object[]{value}); OnValueChanged(invokee, EventArgs.Empty); } catch (Exception t) { // Give ourselves a chance to unwind properly before rethrowing the exception (bug# 20221). // value = oldValue; // If there was a problem setting the controls property then we get: // ArgumentException (from properties set method) // ==> Becomes inner exception of TargetInvocationException // ==> caught here if (t is TargetInvocationException && t.InnerException != null) { // Propagate the original exception up throw t.InnerException; } else { throw t; } } } finally { // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, this, oldValue, value); } } } } } /// <devdoc> /// Indicates whether the value of this property needs to be persisted. In /// other words, it indicates whether the state of the property is distinct /// from when the component is first instantiated. If there is a default /// value specified in this DebugReflectPropertyDescriptor, it will be compared against the /// property's current value to determine this. If there is't, the /// ShouldSerializeXXX method is looked for and invoked if found. If both /// these routes fail, true will be returned. /// /// If this returns false, a tool should not persist this property's value. /// </devdoc> public override bool ShouldSerializeValue(object component) { component = GetDebugInvokee(componentClass, component); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); } else if (DefaultValue == noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return true; } return !object.Equals(DefaultValue, GetValue(component)); } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. /// <devdoc> /// A constructor for ReflectPropertyDescriptors that have no attributes. /// </devdoc> public DebugReflectPropertyDescriptor(Type componentClass, string name, Type type) : this(componentClass, name, type, (Attribute[])null) { } */ } } #endif
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.ObjectModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </remarks> [Layout("SimpleLayout")] [ThreadAgnostic] [ThreadSafe] [AppDomainFixedOutput] public class SimpleLayout : Layout, IUsesStackTrace { private string _fixedText; private string _layoutText; private IRawValue _rawValueRenderer; private IStringValueRenderer _stringValueRenderer; private readonly ConfigurationItemFactory _configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout(string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory) :this(txt, configurationItemFactory, null) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> /// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors.</param> internal SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { _configurationItemFactory = configurationItemFactory; SetLayoutText(txt, throwConfigExceptions); } internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory) { _configurationItemFactory = configurationItemFactory; OriginalText = text; SetRenderers(renderers, text); } /// <summary> /// Original text before compile to Layout renderes /// </summary> public string OriginalText { get; private set; } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get => _layoutText; set => SetLayoutText(value); } private void SetLayoutText(string value, bool? throwConfigExceptions = null) { OriginalText = value; LayoutRenderer[] renderers; string txt; if (value == null) { renderers = ArrayHelper.Empty<LayoutRenderer>(); txt = string.Empty; } else { renderers = LayoutParser.CompileLayout( _configurationItemFactory, new SimpleStringReader(value), throwConfigExceptions, false, out txt); } SetRenderers(renderers, txt); } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText => _fixedText != null; /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText => _fixedText; /// <summary> /// Is the message a simple formatted string? (Can skip StringBuilder) /// </summary> internal bool IsSimpleStringText => _stringValueRenderer != null; /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public ReadOnlyCollection<LayoutRenderer> Renderers { get; private set; } /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> public new StackTraceUsage StackTraceUsage => base.StackTraceUsage; /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout(string text) { if (text == null) return null; return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape(string text) { return text.Replace("${", "${literal:text=${}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var layout = new SimpleLayout(text); return layout.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current object. /// </returns> public override string ToString() { if (string.IsNullOrEmpty(Text) && Renderers?.Count > 0) { return ToStringWithNestedItems(Renderers, r => r.ToString()); } return string.Concat("'", Text, "'"); } internal void SetRenderers(LayoutRenderer[] renderers, string text) { Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers); _fixedText = null; _rawValueRenderer = null; _stringValueRenderer = null; if (Renderers.Count == 0) { _fixedText = string.Empty; } else if (Renderers.Count == 1) { if (Renderers[0] is LiteralLayoutRenderer renderer) { _fixedText = renderer.Text; } else { if (Renderers[0] is IRawValue rawValueRenderer) { _rawValueRenderer = rawValueRenderer; } if (Renderers[0] is IStringValueRenderer stringValueRenderer) { _stringValueRenderer = stringValueRenderer; } } } _layoutText = text; if (LoggingConfiguration != null) { PerformObjectScanning(); } } /// <inheritdoc /> protected override void InitializeLayout() { for (int i = 0; i < Renderers.Count; i++) { LayoutRenderer renderer = Renderers[i]; try { renderer.Initialize(LoggingConfiguration); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.InitializeLayout()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } base.InitializeLayout(); } /// <inheritdoc /> public override void Precalculate(LogEventInfo logEvent) { if (_rawValueRenderer != null) { try { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (ThreadAgnostic && MutableUnsafe) { // If raw value doesn't have the ability to mutate, then we can skip precalculate var success = _rawValueRenderer.TryGetRawValue(logEvent, out var value); if (success && value != null && (Convert.GetTypeCode(value) != TypeCode.Object || value.GetType().IsValueType())) return; } } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in precalculate using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType()); } if (exception.MustBeRethrown()) { throw; } } } base.Precalculate(logEvent); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target); } /// <inheritdoc /> internal override bool TryGetRawValue(LogEventInfo logEvent, out object rawValue) { if (_rawValueRenderer != null) { try { if (!IsInitialized) { Initialize(LoggingConfiguration); } if ((!ThreadAgnostic || MutableUnsafe) && logEvent.TryGetCachedLayoutValue(this, out _)) { rawValue = null; return false; // Raw-Value has been precalculated, so not available } var success = _rawValueRenderer.TryGetRawValue(logEvent, out rawValue); return success; } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in TryGetRawValue using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType()); } if (exception.MustBeRethrown()) { throw; } } } rawValue = null; return false; } /// <inheritdoc /> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return _fixedText; } if (_stringValueRenderer != null) { try { string stringValue = _stringValueRenderer.GetFormattedString(logEvent); if (stringValue != null) return stringValue; _stringValueRenderer = null; // Optimization is not possible } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", _stringValueRenderer?.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } return RenderAllocateBuilder(logEvent); } private void RenderAllRenderers(LogEventInfo logEvent, StringBuilder target) { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Renderers.Count; i++) { LayoutRenderer renderer = Renderers[i]; try { renderer.RenderAppendBuilder(logEvent, target); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } } /// <inheritdoc /> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { if (IsFixedText) { target.Append(_fixedText); return; } RenderAllRenderers(logEvent, target); } } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com namespace DSPUtil { [Serializable] public class LinearEnvelope : SoundObj { // Linear envelope: // apply a linear-time linear-gain change from startGain (dB) to endGain (dB) // over the course of nSamples private double _startGain; private double _endGain; private int _nSamples; public LinearEnvelope(double dBstartGain, double dBendGain, int nSamples) { _startGain = MathUtil.gain(dBstartGain); _endGain = MathUtil.gain(dBendGain); _nSamples = nSamples; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int n = 0; // Multiply each input sample // by the instantaneous gain we want foreach (ISample sample in Input) { double frac = (double)n / (double)_nSamples; double gain = _startGain + frac * (_endGain - _startGain); Sample s = new Sample( sample, gain ); n++; yield return s; } } } } [Serializable] public class LinearDbEnvelope : SoundObj { // Linear envelope: // apply a linear-time log-gain change from startGain (dB) to endGain (dB) // over the course of nSamples private double _startGain; private double _endGain; private int _nSamples; public LinearDbEnvelope(double dBstartGain, double dBendGain, int nSamples) { _startGain = dBstartGain; _endGain = dBendGain; _nSamples = nSamples; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int n = 0; // Multiply each input sample // by the instantaneous gain we want foreach (ISample sample in Input) { double frac = (double)n / (double)_nSamples; double gain = _startGain + frac * (_endGain - _startGain); Sample s = new Sample(sample, MathUtil.gain(gain));; n++; yield return s; } } } } [Serializable] public class CosWindow : SoundObj { // A cosine-based window function // centered on sample # 'center' // returns the full input stream, muted outside the windowed region private int _center; private int _sidewidth; private int _halfplateauwidth; private double _c0; private double _c1; private double _c2; private double _c3; public CosWindow(int center, int sidewidth, int halfplateauwidth, double c0, double c1, double c2, double c3) { _center = center; _sidewidth = sidewidth; _halfplateauwidth = halfplateauwidth; _c0 = c0; _c1 = c1; _c2 = c2; _c3 = c3; } public IEnumerator<double> Gains { get { int n = 0; int nstart = _center - _halfplateauwidth - _sidewidth; int nend = _center + _halfplateauwidth + _sidewidth; int plateaustart = _center - _halfplateauwidth; int plateauend = _center + _halfplateauwidth; while (true) { double gain = 0; if (n < nstart) { //gain = 0; } else if (n > nend) { //gain = 0; } else if (n > plateaustart && n < plateauend) { gain = 1; } else { // Raised Cosine: 0.5* ( cos(phi) + 1 ), from phi=pi to 2pi // long nn = (long)n - _center; if (nn < 0) { nn += (long)_halfplateauwidth; } else { nn -= (long)_halfplateauwidth; } long N = (long)_sidewidth; if (Math.Abs(nn) < 2 * N) { double phi = Math.PI * ((double)nn / N); gain = _c0 + (_c1 * Math.Cos(phi)) + (_c2 * Math.Cos(2 * phi)) + (_c3 * Math.Cos(3 * phi)); } } n++; yield return gain; } } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } IEnumerator<double> gains = Gains; foreach (ISample sample in _input) { gains.MoveNext(); double gain = gains.Current; Sample s = new Sample(sample, gain); yield return s; } } } } // The usual types of cosine-based windows, centered, with no additional plateau // and acting as filters, i.e. only returning the portion of the stream which lies within the window [Serializable] public class Hann : CosWindow { public Hann(int center, int sidewidth) : base(center, sidewidth, 0, 0.5, 0.5, 0, 0) { } } [Serializable] public class Hamming : CosWindow { public Hamming(int center, int sidewidth) : base(center, sidewidth, 0, 0.54, 0.46, 0, 0) { } public Hamming(int center, int sidewidth, int halfplateauwidth) : base(center, sidewidth, halfplateauwidth, 0.54, 0.46, 0, 0) { } } [Serializable] public class Blackman : CosWindow { public Blackman(int center, int sidewidth) : base(center, sidewidth, 0, 0.42, 0.5, 0.08, 0) { } public Blackman(int center, int sidewidth, int halfplateauwidth) : base(center, sidewidth, halfplateauwidth, 0.42, 0.5, 0.08, 0) { } } [Serializable] public class BlackmanHarris : CosWindow { public BlackmanHarris(int center, int sidewidth) : base(center, sidewidth, 0, 0.35875, 0.48829, 0.14128, 0.01168) { } public BlackmanHarris(int center, int sidewidth, int halfplateauwidth) : base(center, sidewidth, halfplateauwidth, 0.35875, 0.48829, 0.14128, 0.01168) { } } [Serializable] public class NormalWindow : SoundObj { private int _center; private int _plateau; private double _sigma; /// <summary> /// A normal distribution around the center, with std deviation of 'sigma' samples /// (e.g. use center=N/2, sigma=N/6 to cover most of the curve). /// The window hiehgt is set such that the center sample is unchanged (per most windows). /// rather than normalizing area under the curve. /// </summary> public NormalWindow(int center, double sigma) { _center = center; _plateau = 0; _sigma = sigma; } public NormalWindow(int center, int plateau, double sigma) { _center = center; _plateau = plateau; _sigma = sigma; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int n = 0; // double mul = 1/(_sigma * Math.Sqrt(2*Math.PI)); double sig2 = 2 * _sigma * _sigma; foreach (ISample sample in Input) { long nn = (long)_center - (long)n; double gain = 1; // tbd: plateau gain = Math.Exp(-(nn * nn / sig2)); // * mul; to normalize Sample s = new Sample(sample, gain); n++; yield return s; } } } } [Serializable] public class ShelfEnvelope : SoundObj { // "Raised sine shelf" envelope: // given // start gain: dB // end gain: dB // start sample # // end sample # // apply a raised-sine envelope between start and end. private double _startGain; private double _endGain; private int _startSample; private int _endSample; public ShelfEnvelope(double dBstartGain, double dBendGain, int startSample, int endSample) { _startGain = dBstartGain; _endGain = dBendGain; _startSample = startSample; _endSample = endSample; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int n = 0; // Multiply each input sample // by the instantaneous gain we want foreach (ISample sample in Input) { double gain; if (n < _startSample) { gain = _startGain; } else if (n > _endSample) { gain = _endGain; } else { // Raised Cosine: 0.5* ( cos(phi) + 1 ), from phi=pi to 2pi // double frac = (double)(n - _startSample) / (double)(_endSample - _startSample); double phi = Math.PI * (1 + frac); double rcos = ( 1 + Math.Cos(phi) )/2; gain = _startGain + rcos * (_endGain - _startGain); } Sample s = new Sample( sample, MathUtil.gain(gain) ); n++; yield return s; } } } } [Serializable] public class LogBasisShelfEnvelope : SoundObj { // "Raised sine shelf" envelope: // given // start gain: dB // end gain: dB // start sample # // end sample # // apply a raised-sine envelope between start and end, with log scale // (e.g. suitable for use on frequency-domain data) private double _startGain; private double _endGain; private int _startSample; private int _endSample; public LogBasisShelfEnvelope(double dBstartGain, double dBendGain, int startSample, int endSample) { _startGain = dBstartGain; _endGain = dBendGain; _startSample = startSample; _endSample = endSample; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int n = 0; // Add 1 so we don't blow up when starting from zero double logStart = Math.Log(1+_startSample); double logEnd = Math.Log(1+_endSample); // Multiply each input sample // by the instantaneous gain we want foreach (ISample sample in Input) { double gain; if (n < _startSample) { gain = _startGain; } else if (n > _endSample) { gain = _endGain; } else { // Raised Cosine: 0.5* ( cos(phi) + 1 ), from phi=pi to 2pi // // fraction 0 to 1, linear basis // double frac = (double)(n - _startSample) / (double)(_endSample - _startSample); // fraction 0 to 1, log basis double frac = (Math.Log(n + 1) - logStart) / (logEnd - logStart); double phi = Math.PI * (1 + frac); double rcos = (1 + Math.Cos(phi)) / 2; gain = _startGain + rcos * (_endGain - _startGain); } Sample s = new Sample( sample, MathUtil.gain(gain) ); n++; yield return s; } } } } }
/********************************************************************************************** * Copyright 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file * except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under the License. * * ******************************************************************************************** * * Amazon Product Advertising API * Signed Requests Sample Code * * API Version: 2009-03-31 * */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Browser; using System.Security.Cryptography; using Microsoft.Collections.Generic; namespace AmazonSearch.Data { class SignedRequestHelper { private string endPoint; private string akid; private byte[] secret; private HMAC signer; private const string REQUEST_URI = "/onca/xml"; private const string REQUEST_METHOD = "GET"; /* * Use this constructor to create the object. The AWS credentials are available on * http://aws.amazon.com * * The destination is the service end-point for your application: * US: ecs.amazonaws.com * JP: ecs.amazonaws.jp * UK: ecs.amazonaws.co.uk * DE: ecs.amazonaws.de * FR: ecs.amazonaws.fr * CA: ecs.amazonaws.ca */ public SignedRequestHelper(string awsAccessKeyId, string awsSecretKey, string destination) { this.endPoint = destination.ToLower(); this.akid = awsAccessKeyId; this.secret = Encoding.UTF8.GetBytes(awsSecretKey); this.signer = new HMACSHA256(this.secret); } /* * Sign a request in the form of a Dictionary of name-value pairs. * * This method returns a complete URL to use. Modifying the returned URL * in any way invalidates the signature and Amazon will reject the requests. */ public string Sign(IDictionary<string, string> request) { // Use a SortedDictionary to get the parameters in naturual byte order, as // required by AWS. ParamComparer pc = new ParamComparer(); SortedDictionary<string, string> sortedMap = new SortedDictionary<string, string>(request, pc); // Add the AWSAccessKeyId and Timestamp to the requests. sortedMap["AWSAccessKeyId"] = this.akid; sortedMap["Timestamp"] = this.GetTimestamp(); // Get the canonical query string string canonicalQS = this.ConstructCanonicalQueryString(sortedMap); // Derive the bytes needs to be signed. StringBuilder builder = new StringBuilder(); builder.Append(REQUEST_METHOD) .Append("\n") .Append(this.endPoint) .Append("\n") .Append(REQUEST_URI) .Append("\n") .Append(canonicalQS); string stringToSign = builder.ToString(); byte[] toSign = Encoding.UTF8.GetBytes(stringToSign); // Compute the signature and convert to Base64. byte[] sigBytes = signer.ComputeHash(toSign); string signature = Convert.ToBase64String(sigBytes); // now construct the complete URL and return to caller. StringBuilder qsBuilder = new StringBuilder(); qsBuilder.Append("http://") .Append(this.endPoint) .Append(REQUEST_URI) .Append("?") .Append(canonicalQS) .Append("&Signature=") .Append(this.PercentEncodeRfc3986(signature)); return qsBuilder.ToString(); } /* * Sign a request in the form of a query string. * * This method returns a complete URL to use. Modifying the returned URL * in any way invalidates the signature and Amazon will reject the requests. */ public string Sign(string queryString) { IDictionary<string, string> request = this.CreateDictionary(queryString); return this.Sign(request); } /* * Current time in IS0 8601 format as required by Amazon */ private string GetTimestamp() { DateTime currentTime = DateTime.UtcNow; string timestamp = currentTime.ToString("yyyy-MM-ddTHH:mm:ssZ"); return timestamp; } /* * Percent-encode (URL Encode) according to RFC 3986 as required by Amazon. * * This is necessary because .NET's HttpUtility.UrlEncode does not encode * according to the above standard. Also, .NET returns lower-case encoding * by default and Amazon requires upper-case encoding. */ private string PercentEncodeRfc3986(string str) { str = HttpUtility.UrlEncode(str); //str = HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8); str.Replace("'", "%27").Replace("(", "%28").Replace(")", "%29").Replace("*", "%2A").Replace("!", "%21").Replace("%7e", "~").Replace("+", "%20"); StringBuilder sbuilder = new StringBuilder(str); for (int i = 0; i < sbuilder.Length; i++) { if (sbuilder[i] == '%') { if (Char.IsDigit(sbuilder[i + 1]) && Char.IsLetter(sbuilder[i + 2])) { sbuilder[i + 2] = Char.ToUpper(sbuilder[i + 2]); } } } return sbuilder.ToString(); } /* * Convert a query string to corresponding dictionary of name-value pairs. */ private IDictionary<string, string> CreateDictionary(string queryString) { Dictionary<string, string> map = new Dictionary<string, string>(); string[] requestParams = queryString.Split('&'); for (int i = 0; i < requestParams.Length; i++) { if (requestParams[i].Length < 1) { continue; } char[] sep = { '=' }; string[] param = requestParams[i].Split(sep); for (int j = 0; j < param.Length; j++) { param[j] = HttpUtility.UrlDecode(param[j]); //param[j] = HttpUtility.UrlDecode(param[j], System.Text.Encoding.UTF8); } switch (param.Length) { case 1: { if (requestParams[i].Length >= 1) { if (requestParams[i].ToCharArray()[0] == '=') { map[""] = param[0]; } else { map[param[0]] = ""; } } break; } case 2: { if (!string.IsNullOrEmpty(param[0])) { map[param[0]] = param[1]; } } break; } } return map; } /* * Consttuct the canonical query string from the sorted parameter map. */ private string ConstructCanonicalQueryString(SortedDictionary<string, string> sortedParamMap) { StringBuilder builder = new StringBuilder(); if (sortedParamMap.Count == 0) { builder.Append(""); return builder.ToString(); } foreach (KeyValuePair<string, string> kvp in sortedParamMap) { builder.Append(this.PercentEncodeRfc3986(kvp.Key)); builder.Append("="); builder.Append(this.PercentEncodeRfc3986(kvp.Value)); builder.Append("&"); } string canonicalString = builder.ToString(); canonicalString = canonicalString.Substring(0, canonicalString.Length - 1); return canonicalString; } } /* * To help the SortedDictionary order the name-value pairs in the correct way. */ class ParamComparer : IComparer<string> { public int Compare(string p1, string p2) { return string.CompareOrdinal(p1, p2); } } }
using System; using System.Runtime.InteropServices; using System.Collections; using System.Text; using System.Threading; using System.IO.Ports; namespace Hydra.Framework.Mapping.Gps { // // ********************************************************************** /// <summary> /// Class for handling serial communications with the GPS receiver /// </summary> // ********************************************************************** // public class SerialPort : IDisposable { #region Private Member Variables // // ********************************************************************** /// <summary> /// Set default timeout to 5 seconds /// </summary> // ********************************************************************** // private int m_TimeOut = 5; // // ********************************************************************** /// <summary> /// Time Since Last Event /// </summary> // ********************************************************************** // private long m_TimeSinceLastEvent; // // ********************************************************************** /// <summary> /// Has been Timedout /// </summary> // ********************************************************************** // private bool m_HasTimedOut; // // ********************************************************************** /// <summary> /// Receive Byte Threshold /// </summary> // ********************************************************************** // private const int m_ReceivedBytesThreshold = 200; // // ********************************************************************** /// <summary> /// Serial Port IO /// </summary> // ********************************************************************** // private System.IO.Ports.SerialPort m_SerialPort; // // ********************************************************************** /// <summary> /// Is the Object Disposed /// </summary> // ********************************************************************** // private bool m_IsDisposed = false; #endregion #region Deleages & Events // // ********************************************************************** /// <summary> /// Delegate type for hooking up change notifications. /// </summary> // ********************************************************************** // public delegate void NewGPSDataHandler(object sender, GPSEventArgs e); // // ********************************************************************** /// <summary> /// Event fired whenever new GPS data is acquired from the receiver. /// </summary> // ********************************************************************** // public event NewGPSDataHandler NewGPSData; #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initilializes the serialport /// </summary> // ********************************************************************** // public SerialPort() { m_SerialPort = new System.IO.Ports.SerialPort(); m_IsDisposed = false; } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="SerialPort"/> class. /// </summary> /// <param name="SerialPort">The serial port.</param> /// <param name="BaudRate">The baud rate.</param> // ********************************************************************** // public SerialPort(string SerialPort, int BaudRate) { m_SerialPort = new System.IO.Ports.SerialPort(SerialPort, BaudRate); m_IsDisposed = false; } #endregion #region Disposal // // ********************************************************************** /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> // ********************************************************************** // public void Dispose() { if (!this.m_IsDisposed) { this.Stop(); m_SerialPort = null; } m_IsDisposed = true; // // Take yourself off the Finalization queue // to prevent finalization code for this object // from executing a second time. // GC.SuppressFinalize(this); } // // ********************************************************************** /// <summary> /// Finalizer /// </summary> // ********************************************************************** // ~SerialPort() { Dispose(); } #endregion #region Properties // // ********************************************************************** /// <summary> /// Gets or sets the timeout in seconds. /// <remarks>5 second default</remarks> /// </summary> /// <value>The time out.</value> // ********************************************************************** // public int TimeOut { get { return m_TimeOut; } set { m_TimeOut = value; } } // // ********************************************************************** /// <summary> /// Serial port /// </summary> /// <value>The port.</value> // ********************************************************************** // public string Port { get { return m_SerialPort.PortName; } set { m_SerialPort.PortName = value; } } // // ********************************************************************** /// <summary> /// BaudRate /// </summary> /// <value>The baud rate.</value> // ********************************************************************** // public int BaudRate { get { return m_SerialPort.BaudRate; } set { m_SerialPort.BaudRate = value; } } // // ********************************************************************** /// <summary> /// Species whether the serialport is open or not /// </summary> /// <value> /// <c>true</c> if this instance is port open; otherwise, <c>false</c>. /// </value> // ********************************************************************** // public bool IsPortOpen { get { return m_SerialPort.IsOpen; } } #endregion #region Private Methods // // ********************************************************************** /// <summary> /// Opens the GPS port ans starts parsing data /// </summary> // ********************************************************************** // private void Open() { m_TimeSinceLastEvent = DateTime.Now.Ticks; m_HasTimedOut = false; m_SerialPort.Open(); } // // ********************************************************************** /// <summary> /// Opens the serial port and starts parsing NMEA data. Returns when the port is closed. /// </summary> // ********************************************************************** // public void Start() { Read(); } // // ********************************************************************** /// <summary> /// Check the serial port for data. If data is available, data is read and parsed. /// This is a loop the keeps running until the port is closed. /// </summary> // ********************************************************************** // private void Read() { int MilliSecondsWait = 10; string strData = ""; this.Open(); while (m_SerialPort.IsOpen) { int nBytes = m_SerialPort.BytesToRead; byte[] BufBytes; BufBytes = new byte[nBytes]; m_SerialPort.Read(BufBytes, 0, nBytes); strData += Encoding.GetEncoding("ASCII").GetString(BufBytes, 0, nBytes); string temp = ""; while (strData != temp) { temp = strData; strData = GetNmeaString(strData); } Thread.Sleep(MilliSecondsWait); if (DateTime.Now.Ticks - m_TimeSinceLastEvent > 10000000 * m_TimeOut && !m_HasTimedOut) { m_HasTimedOut = true; FireEvent(GPSEventType.TimeOut, ""); } } } // // ********************************************************************** /// <summary> /// Writes data to serial port. This is useful for sending DGPS data to the device. /// </summary> /// <param name="BufBytes">Data to write to serial port</param> // ********************************************************************** // public void Write(byte[] BufBytes) { m_SerialPort.Write(BufBytes, 0, BufBytes.Length); } // // ********************************************************************** /// <summary> /// Fires a NewGPSFix event /// </summary> /// <param name="type">Type of GPS event (GPGGA, GPGSA, etx...)</param> /// <param name="sentence">NMEA Sentence</param> // ********************************************************************** // private void FireEvent(GPSEventType type, string sentence) { GPSEventArgs e = new GPSEventArgs(); e.TypeOfEvent = type; e.Sentence = sentence; NewGPSData(this, e); } // // ********************************************************************** /// <summary> /// Closes the port and ends the thread. /// </summary> // ********************************************************************** // public void Stop() { if (m_SerialPort != null) if (m_SerialPort.IsOpen) m_SerialPort.Close(); } // // ********************************************************************** /// <summary> /// Extracts a full NMEA string from the data recieved on the serialport, and parses this. /// The remaining and unparsed NMEA string is returned. /// </summary> /// <param name="strNMEA">NMEA ASCII data</param> /// <returns>Unparsed NMEA data</returns> // ********************************************************************** // private string GetNmeaString(string strNMEA) { strNMEA = strNMEA.Replace("\n", "").Replace("\r", ""); // Remove linefeeds int nStart = strNMEA.IndexOf("$"); // Position of first NMEA data if (nStart < 0 || nStart == strNMEA.Length - 2) return strNMEA; // // This will never pass the last NMEA sentence, before the next one arrives // The following should instead stop at the end of the line. // int nStop = strNMEA.IndexOf("$", nStart + 1); //Position of next NMEA sentence if (nStop > -1) { string strData; strData = strNMEA.Substring(nStart, nStop - nStart).Trim(); if (strData.StartsWith("$")) { m_HasTimedOut = false; m_TimeSinceLastEvent = DateTime.Now.Ticks; if (CheckSentence(strData)) FireEvent(GPSHandler.String2Eventtype(strData), strData); } return strNMEA.Substring(nStop); } else return strNMEA; } // // ********************************************************************** /// <summary> /// Checks the checksum of a NMEA sentence /// </summary> /// <param name="strSentence">NMEA Sentence</param> /// <returns>'true' of checksum is correct</returns> /// <remarks> /// The optional checksum field consists of a "*" and two hex digits /// representing the exclusive OR of all characters between, but not /// including, the "$" and "*". A checksum is required on some /// sentences. /// </remarks> // ********************************************************************** // private bool CheckSentence(string strSentence) { int iStart = strSentence.IndexOf('$'); int iEnd = strSentence.IndexOf('*'); // // If start/stop isn't found it probably doesn't contain a checksum, // or there is no checksum after *. In such cases just return true. // if (iStart >= iEnd || iEnd + 3 > strSentence.Length) return true; byte result = 0; for (int i = iStart + 1; i < iEnd; i++) result ^= (byte)strSentence[i]; return (result.ToString("X") == strSentence.Substring(iEnd + 1, 2)); } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is DotSpatial.dll for the DotSpatial project // // The Initial Developer of this Original Code is Ted Dunsford. Created in January 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; namespace DotSpatial.Data { /// <summary> /// Handles the native file functions for float grids, without relying on GDAL. /// </summary> public class Raster : RasterBoundDataSet, IRaster { #region Events /// <summary> /// Occurs when attempting to copy or save to a fileName that already exists. A developer can tap into this event /// in order to display an appropriate message. A cancel property allows the developer (and ultimately the user) /// decide if the specified event should ultimately be canceled. /// </summary> public event EventHandler<MessageCancelEventArgs> FileExists; #endregion #region Private Variables // This stores a counter for processes that need to modify progress messages to take into account multiple bands. // The data type like long, int, etc in a binary grid. // The file format for the grid... this should only be Binary or ASCII // String fileName private double _maximum; private double _mean; private double _minimum; // A float for no-data values private int _numColumns; // The count of the columns in the image private int _numRows; // The number of rows in an image // todo: determine where _progressHandler should be used // private IProgressHandler _progressHandler; private List<IValueRow> _rows; private double _stdDev; private object _tag; private IValueGrid _values; #endregion #region Constructors /// <summary> /// Set up the default values /// </summary> public Raster() { IsInRam = true; Bands = new List<IRaster>(); } #endregion #region Methods /// <summary> /// Creates a memberwise clone of this object. Reference types will be copied, but /// they will still point to the same original object. So a clone of this raster /// is pointing to the same underlying array of values etc. /// </summary> /// <returns>A Raster clone of this raster.</returns> public object Clone() { return MemberwiseClone(); } /// <summary> /// Creates a new IRaster that has the identical characteristics and in-ram data to the original. /// </summary> /// <returns>A Copy of the original raster.</returns> public virtual IRaster Copy() { throw new NotImplementedException("Copy should be implemented in the internal, or sub classes."); } /// <summary> /// Creates a duplicate version of this file. If copyValues is set to false, then a raster of NoData values is created /// that has the same georeferencing information as the source file of this Raster, even if this raster is just a window. /// </summary> /// <param name="fileName">The string fileName specifying where to create the new file.</param> /// <param name="copyValues">If this is false, the same size and georeferencing values are used, but they are all set to NoData.</param> public virtual void Copy(string fileName, bool copyValues) { throw new NotImplementedException("Copy should be implemented in the internal, or sub classes."); } /// <inheritdoc/> public virtual List<double> GetValues(IEnumerable<long> indices) { //Implemented in subclass return null; } /// <summary> /// Even if this is a window, this will cause this raster to show statistics calculated from the entire file. /// </summary> public virtual void GetStatistics() { throw new NotImplementedException(DataStrings.NotImplemented); } /// <summary> /// Gets or sets a statistical sampling. This is designed to cache a small, /// representative sample of no more than about 10,000 values. This property /// does not automatically produce the sample, and so this can be null. /// </summary> public IEnumerable<double> Sample { get; set; } /// <summary> /// Saves the values to a the same file that was created or loaded. /// </summary> public virtual void Save() { throw new NotImplementedException(DataStrings.NotImplemented); } /// <summary> /// Saves the curretn raster to the specified file. The current driver code and options are used. /// </summary> /// <param name="fileName">The string fileName to save the raster to.</param> public virtual void SaveAs(string fileName) { SaveAs(fileName, DriverCode, Options); } /// <inheritdoc/> public virtual IRaster ReadBlock(int xOff, int yOff, int sizeX, int sizeY) { // Implemented in Subclass return null; } /// <inheritdoc/> public virtual void WriteBlock(IRaster blockValues, int xOff, int yOff, int xSize, int ySize) { // Implemented in subclass } /// <summary> /// This code is empty, but can be overridden in subtypes /// </summary> /// <param name="original"></param> public virtual void SetData(IRaster original) { } /// <summary> /// Instructs the file to write header changes only. This is espcially useful for changing the /// extents without altering the actual raster values themselves. /// </summary> public virtual void WriteHeader() { // Implemented in Sublcasses } /// <summary> /// This create new method implies that this provider has the priority for creating a new file. /// An instance of the dataset should be created and then returned. By this time, the fileName /// will already be checked to see if it exists, and deleted if the user wants to overwrite it. /// </summary> /// <param name="name">The string fileName for the new instance.</param> /// <param name="driverCode">The string short name of the driver for creating the raster.</param> /// <param name="xSize">The number of columns in the raster.</param> /// <param name="ySize">The number of rows in the raster.</param> /// <param name="numBands">The number of bands to create in the raster.</param> /// <param name="dataType">The data type to use for the raster.</param> /// <param name="options">The options to be used.</param> public static IRaster Create(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { return DataManager.DefaultDataManager.CreateRaster(name, driverCode, xSize, ySize, numBands, dataType, options); } /// <summary> /// Gets the no data cell count. Calls GetStatistics() internally. /// </summary> /// <returns>The number of cells which are equal to NoDataValue.</returns> public long GetNoDataCellCount() { GetStatistics(); return (this.NumColumns * this.NumRows) - this.NumValueCells; } /// <summary> /// Opens the specified fileName. The DefaultDataManager will determine the best type of raster to handle the specified /// file based on the fileName or characteristics of the file. /// </summary> /// <param name="fileName">The string fileName of the raster to open.</param> public static IRaster Open(string fileName) { return DataManager.DefaultDataManager.OpenRaster(fileName, true, DataManager.DefaultDataManager.ProgressHandler); } /// <summary> /// Opens the specified fileName. The DefaultDataManager will determine the best type of raster to handle the specified /// file based on the fileName or characteristics of the file. /// </summary> public virtual void Open() { } /// <summary> /// Saves the current raster to the specified file, using the specified driver, but with the /// options currently specified in the Options property. /// </summary> /// <param name="fileName">The string fileName to save this raster as</param> /// <param name="driverCode">The string driver code.</param> public virtual void SaveAs(string fileName, string driverCode) { SaveAs(fileName, driverCode, Options); } /// <summary> /// Saves the current raster to the specified file. /// </summary> /// <param name="fileName">The string fileName to save the current raster to.</param> /// <param name="driverCode">The driver code to use.</param> /// <param name="options">the string array of options that depend on the format.</param> public virtual void SaveAs(string fileName, string driverCode, string[] options) { // Create a new raster file IRaster newRaster = DataManager.DefaultDataManager.CreateRaster(fileName, driverCode, NumColumns, NumRows, NumBands, DataType, options); // Copy the file based values // newRaster.Copy(Filename, true); newRaster.Projection = Projection; newRaster.Extent = Extent; // Copy the in memory value newRaster.SetData(this); newRaster.ProgressHandler = ProgressHandler; newRaster.NoDataValue = NoDataValue; newRaster.GetStatistics(); newRaster.Bounds = this.Bounds; // Save the in-memory values. newRaster.Save(); newRaster.Close(); } #endregion #region Properties /// <summary> /// A parameter for accessing some GDAL data. This frequently does nothing and is usually 0. /// </summary> public int LineSpace { get; set; } /// <summary> /// A parameter for accessing GDAL. This frequently does nothing and is usually 0. /// </summary> public int PixelSpace { get; set; } /// <summary> /// Gets the size of each raster element in bytes. /// </summary> public virtual int ByteSize { get { throw new NotImplementedException( "This should be implemented at a level where a type parameter can be parsed."); } } /// <summary> /// Gets or sets the list of bands, which are in turn rasters. The rasters /// contain only one band each, instead of the list of all the bands like the /// parent raster. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IList<IRaster> Bands { get; set; } /// <summary> /// The geographic height of a cell the projected units. Setting this will /// automatically adjust the affine coefficient to a negative value. /// </summary> [Category("General")] [Description("The geographic height of a cell the projected units. Setting this will automatically adjust the affine coefficient to a negative value.")] public virtual double CellHeight { get { if (Bounds != null) return Math.Abs(Bounds.AffineCoefficients[5]); return 0; } set { // For backwards compatibility, people specifying CellHeight can be assumed // to want to preserve YllCenter, and not the Affine coefficient. Bounds.AffineCoefficients[3] = Bounds.BottomLeft().Y + value * NumRows; // This only allows you to change the magnitude of the cell height, not the direction. // For changing direction, control AffineCoefficients[5] directly. Bounds.AffineCoefficients[5] = Math.Sign(Bounds.AffineCoefficients[5]) * Math.Abs(value); } } /// <summary> /// The geographic width of a cell in the projected units /// </summary> [Category("General")] [Description("The geographic width of a cell in the projected units.")] public virtual double CellWidth { get { return Math.Abs(Bounds.AffineCoefficients[1]); } set { Bounds.AffineCoefficients[1] = Math.Sign(Bounds.AffineCoefficients[1]) * Math.Abs(value); } } /// <summary> /// This provides a zero-based integer band index that specifies which of the internal bands /// is currently being used for requests for data. /// </summary> [Category("Data")] [Description("This provides a zero-based integer band index that specifies which of the internal bands is currently being used for requests for data.")] public virtual int CurrentBand { get; protected set; } /// <summary> /// This does nothing unless the FileType property is set to custom. /// In such a case, this string allows new file types to be managed. /// </summary> [Category("Data")] [Description("This does nothing unless the FileType property is set to custom. In such a case, this string allows new file types to be managed.")] public virtual string CustomFileType { get; protected set; } /// <summary> /// This returns the RasterDataTypes enumeration clarifying the underlying data type for this raster. /// </summary> [Category("Data")] [Description("This returns the RasterDataTypes enumeration clarifying the underlying data type for this raster.")] public Type DataType { get; set; } /// <summary> /// Gets or sets the driver code for this raster. /// </summary> public string DriverCode { get; set; } /// <summary> /// The integer column index for the right column of this raster. Most of the time this will /// be NumColumns - 1. However, if this raster is a window taken from a larger raster, then /// it will be the index of the endColumn from the window. /// </summary> [Category("Window")] [Description("The integer column index for the right column of this raster. Most of the time this will be NumColumns - 1. However, if this raster is a window taken from a larger raster, then it will be the index of the endColumn from the window.")] public virtual int EndColumn { get; protected set; } /// <summary> /// The integer row index for the end row of this raster. Most of the time this will /// be numRows - 1. However, if this raster is a window taken from a larger raster, then /// it will be the index of the endRow from the window. /// </summary> [Category("Window")] [Description("The integer row index for the end row of this raster. Most of the time this will be numRows - 1. However, if this raster is a window taken from a larger raster, then it will be the index of the endRow from the window.")] public virtual int EndRow { get; protected set; } /// <summary> /// Returns the grid file type. Only Binary or ASCII are supported natively, without GDAL. /// </summary> [Category("Data")] [Description("Returns the grid file type. Only Binary or ASCII are supported natively, without GDAL.")] public virtual RasterFileType FileType { get; set; } /// <summary> /// Gets or sets a boolean that is true if the data for this raster is in memory. /// </summary> [Category("Data")] [Description("Gets or sets a boolean that is true if the data for this raster is in memory.")] public virtual bool IsInRam { get; protected set; } /// <summary> /// Gets the maximum data value, not counting no-data values in the grid. /// </summary> [Category("Statistics")] [Description("Gets the maximum data value, not counting no-data values in the grid.")] public virtual double Maximum { get { if (Value.Updated) GetStatistics(); return _maximum; } protected set { _maximum = value; } } /// <summary> /// Gets the mean of the non-NoData values in this grid. If the data is not InRam, then /// the GetStatistics method must be called before these values will be correct. /// </summary> [Category("Statistics")] [Description("Gets the mean of the non-NoData values in this grid. If the data is not InRam, then the GetStatistics method must be called before these values will be correct.")] public virtual double Mean { get { if (Value.Updated) GetStatistics(); return _mean; } protected set { _mean = value; } } /// <summary> /// Gets the minimum data value that is not classified as a no data value in this raster. /// </summary> [Category("Statistics")] [Description("Gets the minimum data value that is not classified as a no data value in this raster.")] public virtual double Minimum { get { if (Value.Updated) GetStatistics(); return _minimum; } protected set { _minimum = value; } } /// <summary> /// A double showing the no-data value for this raster. /// </summary> [Category("Data")] [Description("A double showing the no-data value for this raster.")] public virtual double NoDataValue { get; set; } /// <summary> /// For binary rasters this will get cut to only 256 characters. /// </summary> [Category("General")] [Description("For binary rasters this will get cut to only 256 characters.")] public virtual string Notes { get; set; } /// <summary> /// Gets the number of bands. In most traditional grid formats, this is 1. For RGB images, /// this would be 3. Some formats may have many bands. /// </summary> [Category("General")] [Description("Gets the number of bands. In most traditional grid formats, this is 1. For RGB images, this would be 3. Some formats may have many bands.")] public virtual int NumBands { get { return Bands.Count; } } /// <summary> /// Gets the horizontal count of the cells in the raster. /// </summary> [Category("General")] [Description("Gets the horizontal count of the cells in the raster.")] public virtual int NumColumns { get { return _numColumns; } set { _numColumns = value; if (_numColumns > 0 && _numRows > 0 && Bounds != null) { Bounds = new RasterBounds(NumRows, NumColumns, Bounds.AffineCoefficients); } } } /// <summary> /// Gets the integer count of the number of columns in the source or file that this /// raster is a window from. (Usually this will be the same as NumColumns) /// </summary> [Category("Window"), Description("Gets the integer count of the number of columns in the source or file that this raster is a window from. (Usually this will be the same as NumColumns)")] public virtual int NumColumnsInFile { get; protected set; } /// <summary> /// Gets the vertical count of the cells in the raster. /// </summary> [Category("General")] [Description("Gets the vertical count of the cells in the raster.")] public virtual int NumRows { get { return _numRows; } set { _numRows = value; if (_numColumns > 0 && _numRows > 0 && Bounds != null) { Bounds = new RasterBounds(value, NumColumns, Bounds.AffineCoefficients); } } } /// <summary> /// Gets the integer count of the number of rows in the source or file that this /// raster is a window from. (Usually this will be the same as NumColumns.) /// </summary> [Category("Window"), Description("Gets the integer count of the number of rows in the source or file that this raster is a window from. (Usually this will be the same as NumColumns.)")] public virtual int NumRowsInFile { get; protected set; } /// <summary> /// Gets the count of the cells that are not no-data. If the data is not InRam, then /// you will have to first call the GetStatistics() method to gain meaningul values. /// </summary> [Category("Statistics"), Description("Gets the count of the cells that are not no-data. If the data is not InRam, then you will have to first call the GetStatistics() method to gain meaningul values.")] public virtual long NumValueCells { get; protected set; } /// <summary> /// An extra string array of options that exist for support of some types of GDAL supported raster drivers /// </summary> public string[] Options { get; set; } /// <summary> /// Gets a list of the rows in this raster that can be accessed independantly. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual List<IValueRow> Rows { get { return _rows; } protected set { _rows = value; } } /// <summary> /// The integer column index for the left column of this raster. Most of the time this will /// be 0. However, if this raster is a window taken from a file, then /// it will be the row index in the file for the top row of this raster. /// </summary> [Category("Window"), Description("The integer column index for the left column of this raster. Most of the time this will be 0. However, if this raster is a window taken from a larger raster, then it will be the index of the startRow from the window.")] public virtual int StartColumn { get; protected set; } /// <summary> /// The integer row index for the top row of this raster. Most of the time this will /// be 0. However, if this raster is a window taken from a file, then /// it will be the row index in the file for the left row of this raster. /// </summary> [Category("Window"), Description("The integer row index for the top row of this raster. Most of the time this will be 0. However, if this raster is a window taken from a larger raster, then it will be the index of the startRow from the window.")] public virtual int StartRow { get; protected set; } /// <summary> /// Gets the standard deviation of all the Non-nodata cells. If the data is not InRam, /// then you will have to first call the GetStatistics() method to get meaningful values. /// </summary> [Category("Statistics")] [Description("Gets the standard deviation of all the Non-nodata cells. If the data is not InRam, then you will have to first call the GetStatistics() method to get meaningful values.")] public virtual double StdDeviation { get { if (Value.Updated) GetStatistics(); return _stdDev; } protected set { _stdDev = value; } } /// <summary> /// This is provided for future developers to link this raster to other entities. /// It has no function internally, so it can be manipulated safely. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual object Tag { get { return _tag; } set { _tag = value; } } /// <summary> /// Gets or sets the value on the CurrentBand given a row and column undex /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IValueGrid Value { get { return _values; } set { _values = value; } } /// <summary> /// Gets or sets the X position of the lower left data cell. /// Setting this will adjust only the _affine[0] coefficient to ensure that the /// lower left corner ends up in the specified location, while keeping all the /// other affine coefficients the same. This is like a horizontal Translate /// that locks into place the center of the lower left corner of the image. /// </summary> [Category("General")] [Description("Gets or sets the X position of the lower left data cell. " + "Setting this will adjust only the _affine[0] coefficient to ensure that the " + "lower left corner ends up in the specified location, while keeping all the " + "other affine coefficients the same. This is like a horizontal Translate " + "that locks into place the center of the lower left corner of the image.")] public double Xllcenter { get { double[] affine = Bounds.AffineCoefficients; return affine[0] + affine[1] * .5 + affine[2] * (_numColumns - .5); } set { double[] affine = Bounds.AffineCoefficients; if (affine == null) { affine = new double[6]; affine[1] = 1; affine[3] = _numRows; affine[5] = -1; } if (affine[1] == 0) { affine[1] = 1; } affine[0] = value - affine[1] * .5 - affine[2] * (_numColumns - .5); } } /// <summary> /// Gets or sets the Y position of the lower left data cell. /// Setting this will adjust only the _affine[0] coefficient to ensure that the /// lower left corner ends up in the specified location, while keeping all the /// other affine coefficients the same. This is like a horizontal Translate /// that locks into place the center of the lower left corner of the image. /// </summary> [Category("General")] [Description("Gets or sets the Y position of the lower left data cell. " + "Setting this will adjust only the _affine[0] coefficient to ensure that the " + "lower left corner ends up in the specified location, while keeping all the " + "other affine coefficients the same. This is like a horizontal Translate " + "that locks into place the center of the lower left corner of the image.")] public double Yllcenter { get { double[] affine = Bounds.AffineCoefficients; return affine[3] + affine[4] * .5 + affine[5] * (_numRows - .5); } set { double[] affine = Bounds.AffineCoefficients; if (affine == null) { affine = new double[6]; affine[1] = 1; affine[3] = _numRows; } if (affine[5] == 0) { // Cell Height can't be 0 affine[5] = -1; } affine[3] = value - affine[4] * .5 - affine[5] * (_numRows - .5); } } /// <summary> /// By default, Raster does not have any CategoryNames, but this can be overridden /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual String[] CategoryNames() { return null; } /// <summary> /// By default, Raster does not have any CategoryColors, but this can be overridden /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual Color[] CategoryColors() { return null; } #endregion #region Protected Methods /// <summary> /// Gets this raster (or its Internal Raster) as the appropriately typed raster /// so that strong typed access methods are available, instead of just the /// regular methods. /// </summary> /// <typeparam name="T">The type (int, short, float, etc.)</typeparam> /// <returns>The Raster&lt;T&gt; where T are value types like int, short, float"/></returns> public Raster<T> ToRaster<T>() where T : IEquatable<T>, IComparable<T> { return this as Raster<T>; } /// <summary> /// Overrides dispose to correctly handle disposing the objects at the raster level. /// </summary> /// <param name="disposeManagedResources"></param> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { if (Bands != null) { foreach (var r in Bands) { r.Dispose(); } Bands = null; } Bounds = null; CustomFileType = null; DriverCode = null; Filename = null; Notes = null; Options = null; _rows = null; _tag = null; _values = null; } base.Dispose(disposeManagedResources); } /// <summary> /// Fires the FileExists method. If this returns true, then the action should be cancelled. /// </summary> /// <param name="fileName">The fileName to write to</param> /// <returns>Boolean, true if the user doesn't want to overwrite</returns> protected bool OnFileExists(string fileName) { if (FileExists != null) { MessageCancelEventArgs mc = new MessageCancelEventArgs(DataStrings.FileExists_S.Replace("%S", fileName)); FileExists(this, mc); return mc.Cancel; } return false; } /// <summary> /// Gets this raster (or its Internal Raster) as the appropriately typed raster /// so that strong typed access methods are available, instead of just the /// regular methods. /// </summary> /// <returns>A Raster&lt;short&gt;</returns> public Raster<int> ToIntRaster() { return ToRaster<int>(); } /// <summary> /// Gets this raster (or its Internal Raster) as the appropriately typed raster /// so that strong typed access methods are available, instead of just the /// regular methods. /// </summary> /// <returns>A Raster&lt;short&gt;</returns> public Raster<short> ToShortRaster() { return ToRaster<short>(); } /// <summary> /// Gets this raster (or its Internal Raster) as the appropriately typed raster /// so that strong typed access methods are available, instead of just the /// regular methods. /// </summary> /// <returns>A Raster&lt;short&gt;</returns> public Raster<float> ToFloatRaster() { return ToRaster<float>(); } #endregion #region Static Methods /// <summary> /// This create new method implies that this provider has the priority for creating a new file. /// An instance of the dataset should be created and then returned. By this time, the fileName /// will already be checked to see if it exists, and deleted if the user wants to overwrite it. /// </summary> /// <param name="name">The string fileName for the new instance.</param> /// <param name="driverCode">The string short name of the driver for creating the raster.</param> /// <param name="xSize">The number of columns in the raster.</param> /// <param name="ySize">The number of rows in the raster.</param> /// <param name="numBands">The number of bands to create in the raster.</param> /// <param name="dataType">The data type to use for the raster.</param> /// <param name="options">The options to be used.</param> /// <returns>An IRaster</returns> public static IRaster CreateRaster(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { return DataManager.DefaultDataManager.CreateRaster(name, driverCode, xSize, ySize, numBands, dataType, options); } /// <summary> /// For DotSpatial style binary grids, this returns the filetype /// </summary> /// <param name="filename">The fileName with extension to test</param> /// <returns>A GridFileTypes enumeration listing which file type this is</returns> public static RasterFileType GetGridFileType(string filename) { // Get the extension with period from the fileName string extension = Path.GetExtension(filename); // Compare the strings, ignoring case var eUp = extension != null? extension.ToUpper() : string.Empty; switch (eUp) { case ".ASC": return RasterFileType.ASCII; case ".ARC": return RasterFileType.ASCII; case ".BGD": return RasterFileType.BINARY; case ".FLT": return RasterFileType.FLT; case ".ADF": return RasterFileType.ESRI; case ".ECW": return RasterFileType.ECW; case ".BIL": return RasterFileType.BIL; case ".SID": return RasterFileType.MrSID; case ".AUX": return RasterFileType.PAUX; case ".PIX": return RasterFileType.PCIDsk; case ".DHM": return RasterFileType.DTED; case ".DT0": return RasterFileType.DTED; case ".DT1": return RasterFileType.DTED; case ".TIF": return RasterFileType.GeoTiff; case ".IMG": return RasterFileType.BIL; case ".DDF": return RasterFileType.SDTS; } return RasterFileType.CUSTOM; } /// <summary> /// This is significantly m /// </summary> /// <param name="fileName">The string full path for the fileName to open</param> /// <returns>A Raster object which is actually one of the type specific rasters, like FloatRaster.</returns> public static IRaster OpenFile(string fileName) { // Ensure that the fileName is valid if (fileName == null) throw new NullException("fileName"); if (File.Exists(fileName) == false) throw new FileNotFoundException("fileName"); // default to opening values into ram IDataSet dataset = DataManager.DefaultDataManager.OpenFile(fileName); return dataset as IRaster; } /// <summary> /// Returns a native raster of the appropriate file type and data type by parsing the fileName. /// </summary> /// <param name="fileName">The string fileName to attempt to open with a native format</param> /// <param name="inRam">The boolean value.</param> /// <returns>An IRaster which has been opened to the specified file.</returns> public static IRaster OpenFile(string fileName, bool inRam) { // Ensure that the fileName is valid if (fileName == null) throw new NullException("fileName"); if (File.Exists(fileName) == false) throw new FileNotFoundException("fileName"); // default to opening values into ram IDataSet dataset = DataManager.DefaultDataManager.OpenFile(fileName, inRam); return dataset as IRaster; } /// <summary> /// Returns a native raster of the appropriate file type and data type by parsing the fileName. /// </summary> /// <param name="fileName">The string fileName to attempt to open with a native format</param> /// <param name="inRam">The boolean value.</param> /// <param name="progressHandler">An overriding progress manager for this process</param> /// <returns>An IRaster which has been opened to the specified file.</returns> public static IRaster OpenFile(string fileName, bool inRam, IProgressHandler progressHandler) { if (fileName == null) throw new NullException("fileName"); if (File.Exists(fileName) == false) throw new FileNotFoundException("fileName"); // default to opening values into ram IDataSet dataset = DataManager.DefaultDataManager.OpenFile(fileName, inRam, progressHandler); return dataset as IRaster; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Net.Interop; using System; namespace Microsoft.Net.Sockets { public struct TcpServer { IntPtr _handle; public TcpServer(ushort port, byte address1, byte address2, byte address3, byte address4) { var version = new TcpServer.Version(2, 2); WSDATA data; int result = SocketImports.WSAStartup((short)version.Raw, out data); if (result != 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("ERROR: WSAStartup returned {0}", error)); } _handle = SocketImports.socket(ADDRESS_FAMILIES.AF_INET, SOCKET_TYPE.SOCK_STREAM, PROTOCOL.IPPROTO_TCP); if (_handle == IntPtr.Zero) { var error = SocketImports.WSAGetLastError(); SocketImports.WSACleanup(); throw new Exception(String.Format("ERROR: socket returned {0}", error)); } Start(port, address1, address2, address3, address4); } private void Start(ushort port, byte address1, byte address2, byte address3, byte address4) { // BIND in_addr inAddress = new in_addr(); inAddress.s_b1 = address1; inAddress.s_b2 = address2; inAddress.s_b3 = address3; inAddress.s_b4 = address4; sockaddr_in sa = new sockaddr_in(); sa.sin_family = ADDRESS_FAMILIES.AF_INET; sa.sin_port = SocketImports.htons(port); sa.sin_addr = inAddress; int result; unsafe { var size = sizeof(sockaddr_in); result = SocketImports.bind(_handle, ref sa, size); } if (result == SocketImports.SOCKET_ERROR) { SocketImports.WSACleanup(); throw new Exception("bind failed"); } // LISTEN result = SocketImports.listen(_handle, 10); if (result == SocketImports.SOCKET_ERROR) { SocketImports.WSACleanup(); throw new Exception("listen failed"); } } public TcpConnection Accept() { IntPtr accepted = SocketImports.accept(_handle, IntPtr.Zero, 0); if (accepted == new IntPtr(-1)) { var error = SocketImports.WSAGetLastError(); SocketImports.WSACleanup(); throw new Exception(String.Format("listen failed with {0}", error)); } return new TcpConnection(accepted); } public void Stop() { SocketImports.WSACleanup(); } public struct Version { public ushort Raw; public Version(byte major, byte minor) { Raw = major; Raw <<= 8; Raw += minor; } public byte Major { get { UInt16 result = Raw; result >>= 8; return (byte)result; } } public byte Minor { get { UInt16 result = Raw; result &= 0x00FF; return (byte)result; } } public override string ToString() { return String.Format("{0}.{1}", Major, Minor); } } } public struct TcpConnection { IntPtr _handle; public TcpConnection(IntPtr handle) { _handle = handle; } public IntPtr Handle { get { return _handle; } } public int Receive(byte[] bytes) { unsafe { fixed (byte* buffer = bytes) { IntPtr ptr = new IntPtr(buffer); int bytesReceived = SocketImports.recv(Handle, ptr, bytes.Length, 0); if (bytesReceived < 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("receive failed with {0}", error)); } return bytesReceived; } } } public void Close() { SocketImports.closesocket(_handle); } public unsafe int Send(ReadOnlySpan<byte> buffer) { // TODO: This can work with Span<byte> because it's synchronous but we need async pinning support fixed (byte* bytes = &buffer.DangerousGetPinnableReference()) { IntPtr pointer = new IntPtr(bytes); return SendPinned(pointer, buffer.Length); } } public int Send(ReadOnlyBuffer<byte> buffer) { return Send(buffer.Span); } public int Send(ArraySegment<byte> buffer) { return Send(buffer.Array, buffer.Offset, buffer.Count); } public int Send(byte[] bytes, int offset, int count) { unsafe { fixed (byte* buffer = bytes) { IntPtr pointer = new IntPtr(buffer + offset); return SendPinned(pointer, count); } } } public unsafe int Receive(Span<byte> buffer) { // TODO: This can work with Span<byte> because it's synchronous but we need async pinning support fixed (byte* bytes = &buffer.DangerousGetPinnableReference()) { IntPtr pointer = new IntPtr(bytes); return ReceivePinned(pointer, buffer.Length); } } public int Receive(Buffer<byte> buffer) { return Receive(buffer.Span); } public int Receive(ArraySegment<byte> buffer) { return Receive(buffer.Array, buffer.Offset, buffer.Count); } public int Receive(byte[] array, int offset, int count) { unsafe { fixed (byte* buffer = array) { IntPtr pointer = new IntPtr(buffer + offset); return ReceivePinned(pointer, count); } } } private unsafe int SendPinned(IntPtr buffer, int length) { int bytesSent = SocketImports.send(_handle, buffer, length, 0); if (bytesSent == SocketImports.SOCKET_ERROR) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("send failed with {0}", error)); } return bytesSent; } private int ReceivePinned(IntPtr ptr, int length) { int bytesReceived = SocketImports.recv(Handle, ptr, length, 0); if (bytesReceived < 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("receive failed with {0}", error)); } return bytesReceived; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using NodaTime; using QuantConnect.Securities; namespace QuantConnect.Scheduling { /// <summary> /// Provides a builder class to allow for fluent syntax when constructing new events /// </summary> /// <remarks> /// This builder follows the following steps for event creation: /// /// 1. Specify an event name (optional) /// 2. Specify an IDateRule /// 3. Specify an ITimeRule /// a. repeat 3. to define extra time rules (optional) /// 4. Specify additional where clause (optional) /// 5. Register event via call to Run /// </remarks> public class FluentScheduledEventBuilder : IFluentSchedulingDateSpecifier, IFluentSchedulingRunnable { private IDateRule _dateRule; private ITimeRule _timeRule; private Func<DateTime, bool> _predicate; private readonly string _name; private readonly ScheduleManager _schedule; private readonly SecurityManager _securities; /// <summary> /// Initializes a new instance of the <see cref="FluentScheduledEventBuilder"/> class /// </summary> /// <param name="schedule">The schedule to send created events to</param> /// <param name="securities">The algorithm's security manager</param> /// <param name="name">A specific name for this event</param> public FluentScheduledEventBuilder(ScheduleManager schedule, SecurityManager securities, string name = null) { _name = name; _schedule = schedule; _securities = securities; } private FluentScheduledEventBuilder SetTimeRule(ITimeRule rule) { // if it's not set, just set it if (_timeRule == null) { _timeRule = rule; return this; } // if it's already a composite, open it up and make a new composite // prevent nesting composites var compositeTimeRule = _timeRule as CompositeTimeRule; if (compositeTimeRule != null) { var rules = compositeTimeRule.Rules; _timeRule = new CompositeTimeRule(rules.Concat(new[] { rule })); return this; } // create a composite from the existing rule and the new rules _timeRule = new CompositeTimeRule(_timeRule, rule); return this; } #region DateRules and TimeRules delegation /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Every(params DayOfWeek[] days) { _dateRule = _schedule.DateRules.Every(days); return this; } /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay() { _dateRule = _schedule.DateRules.EveryDay(); return this; } /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay(Symbol symbol) { _dateRule = _schedule.DateRules.EveryDay(symbol); return this; } /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart() { _dateRule = _schedule.DateRules.MonthStart(); return this; } /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart(Symbol symbol) { _dateRule = _schedule.DateRules.MonthStart(symbol); return this; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay)); } /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.AfterMarketOpen(Symbol symbol, double minutesAfterOpen, bool extendedMarketOpen) { return SetTimeRule(_schedule.TimeRules.AfterMarketOpen(symbol, minutesAfterOpen, extendedMarketOpen)); } /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.BeforeMarketClose(Symbol symbol, double minuteBeforeClose, bool extendedMarketClose) { return SetTimeRule(_schedule.TimeRules.BeforeMarketClose(symbol, minuteBeforeClose, extendedMarketClose)); } /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.Every(TimeSpan interval) { return SetTimeRule(_schedule.TimeRules.Every(interval)); } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback()); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<DateTime> callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback(time)); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<string, DateTime> callback) { var name = _name ?? _dateRule.Name + ": " + _timeRule.Name; // back the date up to ensure we get all events, the event scheduler will skip past events that whose time has passed var dates = _dateRule.GetDates(_securities.UtcTime.Date.AddDays(-1), Time.EndOfTime); var eventTimes = _timeRule.CreateUtcEventTimes(dates); if (_predicate != null) { eventTimes = eventTimes.Where(_predicate); } var scheduledEvent = new ScheduledEvent(name, eventTimes, callback); _schedule.Add(scheduledEvent); return scheduledEvent; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket) { var security = GetSecurity(symbol); Func<DateTime, bool> predicate = time => { var localTime = time.ConvertFromUtc(security.Exchange.TimeZone); return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket); }; _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(int year, int month, int day) { _dateRule = _schedule.DateRules.On(year, month, day); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(params DateTime[] dates) { _dateRule = _schedule.DateRules.On(dates); return this; } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, 0, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone)); } private Security GetSecurity(Symbol symbol) { Security security; if (!_securities.TryGetValue(symbol, out security)) { throw new Exception(symbol.Permtick + " not found in portfolio. Request this data when initializing the algorithm."); } return security; } #endregion } /// <summary> /// Specifies the date rule component of a scheduled event /// </summary> public interface IFluentSchedulingDateSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events only on the specified date /// </summary> IFluentSchedulingTimeSpecifier On(int year, int month, int day); /// <summary> /// Creates events only on the specified dates /// </summary> IFluentSchedulingTimeSpecifier On(params DateTime[] dates); /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier Every(params DayOfWeek[] days); /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier EveryDay(); /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier EveryDay(Symbol symbol); /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(); /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(Symbol symbol); } /// <summary> /// Specifies the time rule component of a scheduled event /// </summary> public interface IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second = 0); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay); /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable Every(TimeSpan interval); /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false); /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable BeforeMarketClose(Symbol symbol, double minuteBeforeClose = 0, bool extendedMarketClose = false); } /// <summary> /// Specifies the callback component of a scheduled event, as well as final filters /// </summary> public interface IFluentSchedulingRunnable : IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> new IFluentSchedulingRunnable Where(Func<DateTime, bool> predicate); /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable DuringMarketHours(Symbol symbol, bool extendedMarket = false); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<DateTime> callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<string, DateTime> callback); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Microsoft.Xml; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using DataContractDictionary = System.Collections.Generic.Dictionary<Microsoft.Xml.XmlQualifiedName, DataContract>; public sealed class DataContractSerializer : XmlObjectSerializer { private Type _rootType; private DataContract _rootContract; // post-surrogate private bool _needsContractNsAtRoot; private XmlDictionaryString _rootName; private XmlDictionaryString _rootNamespace; private int _maxItemsInObjectGraph; private bool _ignoreExtensionDataObject; private bool _preserveObjectReferences; private ReadOnlyCollection<Type> _knownTypeCollection; internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private DataContractResolver _dataContractResolver; private ISerializationSurrogateProvider _serializationSurrogateProvider; private bool _serializeReadOnlyTypes; public DataContractSerializer(Type type) : this(type, (IEnumerable<Type>)null) { } public DataContractSerializer(Type type, IEnumerable<Type> knownTypes) { Initialize(type, knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, string rootName, string rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes) { XmlDictionary dictionary = new XmlDictionary(2); Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes) { Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false); } #if NET_NATIVE public DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #else internal DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #endif { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver) { Initialize(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, /*dataContractResolver,*/ dataContractResolver, false); } public DataContractSerializer(Type type, DataContractSerializerSettings settings) { if (settings == null) { settings = new DataContractSerializerSettings(); } Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false, settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } private void Initialize(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { CheckNull(type, "type"); _rootType = type; if (knownTypes != null) { this.knownTypeList = new List<Type>(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); } } if (maxItemsInObjectGraph < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", string.Format(SRSerialization.ValueMustBeNonNegative))); _maxItemsInObjectGraph = maxItemsInObjectGraph; _ignoreExtensionDataObject = ignoreExtensionDataObject; _preserveObjectReferences = preserveObjectReferences; _dataContractResolver = dataContractResolver; _serializeReadOnlyTypes = serializeReadOnlyTypes; } private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes); // validate root name and namespace are both non-null _rootName = rootName; _rootNamespace = rootNamespace; } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } public int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal ISerializationSurrogateProvider SerializationSurrogateProvider { get { return _serializationSurrogateProvider; } set { _serializationSurrogateProvider = value; } } public bool PreserveObjectReferences { get { return _preserveObjectReferences; } } public bool IgnoreExtensionDataObject { get { return _ignoreExtensionDataObject; } } public DataContractResolver DataContractResolver { get { return _dataContractResolver; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } private DataContract RootContract { get { if (_rootContract == null) { _rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType)); _needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract); } return _rootContract; } } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteObject(writer, graph, null); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph, dataContractResolver); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { InternalWriteObjectContent(writer, graph, null); } internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; Type graphType = (graph == null) ? declaredType : graph.GetType(); if (_serializationSurrogateProvider != null) { graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType); } if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; if (graph == null) { if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.IsAnyCannotBeNull, declaredType))); WriteNull(writer); } else { if (declaredType == graphType) { if (contract.CanContainReferences) { XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract , dataContractResolver ); context.HandleGraphAtTopLevel(writer, graph, contract); context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } else { contract.WriteXmlValue(writer, graph, null); } } else { XmlObjectSerializerWriteContext context = null; if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType))); contract = GetDataContract(contract, declaredType, graphType); context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract , dataContractResolver ); if (contract.CanContainReferences) { context.HandleGraphAtTopLevel(writer, graph, contract); } context.OnHandleIsReference(writer, contract, graph); context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType); } } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { return declaredTypeContract; } else if (declaredType.IsArray)//Array covariance is not supported in XSD { return declaredTypeContract; } else { return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract); } } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { if (!IsRootXmlAny(_rootName, RootContract)) { writer.WriteEndElement(); } } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { return InternalReadObject(xmlReader, verifyObjectName, null); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; #if NET_NATIVE // Give the root contract a chance to initialize or pre-verify the read RootContract.PrepareToRead(xmlReader); #endif if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { XmlDictionaryString expectedName; XmlDictionaryString expectedNs; if (_rootName == null) { expectedName = RootContract.TopLevelElementName; expectedNs = RootContract.TopLevelElementNamespace; } else { expectedName = _rootName; expectedNs = _rootNamespace; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(string.Format(SRSerialization.ExpectingElement, expectedNs, expectedName), xmlReader)); } } else if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(string.Format(SRSerialization.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader)); } DataContract contract = RootContract; if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType) /*handle Nullable<T> differently*/) { return contract.ReadXmlValue(xmlReader, null); } if (IsRootXmlAny(_rootName, contract)) { return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/); } XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver); return context.InternalDeserialize(xmlReader, _rootType, contract, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsRootElement(reader, RootContract, _rootName, _rootNamespace); } internal override Type GetSerializeType(object graph) { return (graph == null) ? _rootType : graph.GetType(); } internal override Type GetDeserializeType() { return _rootType; } internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType) { object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); if (obj != oldObj) { objType = obj != null ? obj.GetType() : Globals.TypeOfObject; } return obj; } internal static Type GetSurrogatedType(ISerializationSurrogateProvider serializationSurrogateProvider, Type type) { return DataContractSurrogateCaller.GetDataContractType(serializationSurrogateProvider, DataContract.UnwrapNullableType(type)); } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Serialization; using System.Collections; namespace Fungus { /// <summary> /// The type of audio control to perform. /// </summary> public enum ControlAudioType { /// <summary> Play the audiosource once. </summary> PlayOnce, /// <summary> Play the audiosource in a loop. </summary> PlayLoop, /// <summary> Pause a looping audiosource. </summary> PauseLoop, /// <summary> Stop a looping audiosource. </summary> StopLoop, /// <summary> Change the volume level of an audiosource. </summary> ChangeVolume } /// <summary> /// Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped. /// </summary> [CommandInfo("Audio", "Control Audio", "Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.")] [ExecuteInEditMode] public class ControlAudio : Command { [Tooltip("What to do to audio")] [SerializeField] protected ControlAudioType control; public virtual ControlAudioType Control { get { return control; } } [Tooltip("Audio clip to play")] [SerializeField] protected AudioSourceData _audioSource; [Range(0,1)] [Tooltip("Start audio at this volume")] [SerializeField] protected float startVolume = 1; [Range(0,1)] [Tooltip("End audio at this volume")] [SerializeField] protected float endVolume = 1; [Tooltip("Time to fade between current volume level and target volume level.")] [SerializeField] protected float fadeDuration; [Tooltip("Wait until this command has finished before executing the next command.")] [SerializeField] protected bool waitUntilFinished = false; // If there's other music playing in the scene, assign it the same tag as the new music you want to play and // the old music will be automatically stopped. protected virtual void StopAudioWithSameTag() { // Don't stop audio if there's no tag assigned if (_audioSource.Value == null || _audioSource.Value.tag == "Untagged") { return; } var audioSources = GameObject.FindObjectsOfType<AudioSource>(); for (int i = 0; i < audioSources.Length; i++) { var a = audioSources[i]; if (a != _audioSource.Value && a.tag == _audioSource.Value.tag) { StopLoop(a); } } } protected virtual void PlayOnce() { if (fadeDuration > 0) { // Fade volume in LeanTween.value(_audioSource.Value.gameObject, _audioSource.Value.volume, endVolume, fadeDuration ).setOnUpdate( (float updateVolume)=>{ _audioSource.Value.volume = updateVolume; }); } _audioSource.Value.PlayOneShot(_audioSource.Value.clip); if (waitUntilFinished) { StartCoroutine(WaitAndContinue()); } } protected virtual IEnumerator WaitAndContinue() { // Poll the audiosource until playing has finished // This allows for things like effects added to the audiosource. while (_audioSource.Value.isPlaying) { yield return null; } Continue(); } protected virtual void PlayLoop() { if (fadeDuration > 0) { _audioSource.Value.volume = 0; _audioSource.Value.loop = true; _audioSource.Value.GetComponent<AudioSource>().Play(); LeanTween.value(_audioSource.Value.gameObject,0,endVolume,fadeDuration ).setOnUpdate( (float updateVolume)=>{ _audioSource.Value.volume = updateVolume; } ).setOnComplete( ()=>{ if (waitUntilFinished) { Continue(); } } ); } else { _audioSource.Value.volume = endVolume; _audioSource.Value.loop = true; _audioSource.Value.GetComponent<AudioSource>().Play(); } } protected virtual void PauseLoop() { if (fadeDuration > 0) { LeanTween.value(_audioSource.Value.gameObject,_audioSource.Value.volume,0,fadeDuration ).setOnUpdate( (float updateVolume)=>{ _audioSource.Value.volume = updateVolume; } ).setOnComplete( ()=>{ _audioSource.Value.GetComponent<AudioSource>().Pause(); if (waitUntilFinished) { Continue(); } } ); } else { _audioSource.Value.GetComponent<AudioSource>().Pause(); } } protected virtual void StopLoop(AudioSource source) { if (fadeDuration > 0) { LeanTween.value(source.gameObject,_audioSource.Value.volume,0,fadeDuration ).setOnUpdate( (float updateVolume)=>{ source.volume = updateVolume; } ).setOnComplete( ()=>{ source.GetComponent<AudioSource>().Stop(); if (waitUntilFinished) { Continue(); } } ); } else { source.GetComponent<AudioSource>().Stop(); } } protected virtual void ChangeVolume() { LeanTween.value(_audioSource.Value.gameObject,_audioSource.Value.volume,endVolume,fadeDuration ).setOnUpdate( (float updateVolume)=>{ _audioSource.Value.volume = updateVolume; }).setOnComplete( ()=>{ if (waitUntilFinished) { Continue(); } }); } protected virtual void AudioFinished() { if (waitUntilFinished) { Continue(); } } #region Public members public override void OnEnter() { if (_audioSource.Value == null) { Continue(); return; } if (control != ControlAudioType.ChangeVolume) { _audioSource.Value.volume = endVolume; } switch(control) { case ControlAudioType.PlayOnce: StopAudioWithSameTag(); PlayOnce(); break; case ControlAudioType.PlayLoop: StopAudioWithSameTag(); PlayLoop(); break; case ControlAudioType.PauseLoop: PauseLoop(); break; case ControlAudioType.StopLoop: StopLoop(_audioSource.Value); break; case ControlAudioType.ChangeVolume: ChangeVolume(); break; } if (!waitUntilFinished) { Continue(); } } public override string GetSummary() { if (_audioSource.Value == null) { return "Error: No sound clip selected"; } string fadeType = ""; if (fadeDuration > 0) { fadeType = " Fade out"; if (control != ControlAudioType.StopLoop) { fadeType = " Fade in volume to " + endVolume; } if (control == ControlAudioType.ChangeVolume) { fadeType = " to " + endVolume; } fadeType += " over " + fadeDuration + " seconds."; } return control.ToString() + " \"" + _audioSource.Value.name + "\"" + fadeType; } public override Color GetButtonColor() { return new Color32(242, 209, 176, 255); } public override bool HasReference(Variable variable) { return _audioSource.audioSourceRef == variable || base.HasReference(variable); } #endregion #region Backwards compatibility [HideInInspector] [FormerlySerializedAs("audioSource")] public AudioSource audioSourceOLD; protected virtual void OnEnable() { if (audioSourceOLD != null) { _audioSource.Value = audioSourceOLD; audioSourceOLD = null; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aardvark.Base { public class Spectrum { public double FirstWaveLength; public double DeltaWaveLength; public double[] Data; public Spectrum(double firstWaveLength, double deltaWaveLength, double[] data) { FirstWaveLength = firstWaveLength; DeltaWaveLength = deltaWaveLength; Data = data; } public static readonly Spectrum CieXYZ31X = new Spectrum(360, 1, SpectralData.CieXYZ31_X_360_830_1nm); public static readonly Spectrum CieXYZ31Y = new Spectrum(360, 1, SpectralData.CieXYZ31_Y_360_830_1nm); public static readonly Spectrum CieXYZ31Z = new Spectrum(360, 1, SpectralData.CieXYZ31_Z_360_830_1nm); public static readonly Spectrum CieIlluminantA = new Spectrum(300, 1, SpectralData.CieIlluminantA_300_830_1nm); public static readonly Spectrum CieIlluminantD65 = new Spectrum(300, 1, SpectralData.CieIlluminantD65_300_830_1nm); } public static class SpectralData { #region CIE XYZ 1931 Color Matching Functions 360-830nm in 1nm steps public static readonly double[] CieXYZ31_X_360_830_1nm = { 0.0001299, 0.000145847, 0.000163802, 0.000184004, 0.00020669, 0.0002321, 0.000260728, 0.000293075, 0.000329388, 0.000369914, 0.0004149, 0.000464159, 0.000518986, 0.000581854, 0.000655235, 0.0007416, 0.00084503, 0.000964527, 0.001094949, 0.001231154, 0.001368, 0.00150205, 0.001642328, 0.001802382, 0.001995757, 0.002236, 0.002535385, 0.002892603, 0.003300829, 0.003753236, 0.004243, 0.004762389, 0.005330048, 0.005978712, 0.006741117, 0.00765, 0.008751373, 0.01002888, 0.0114217, 0.01286901, 0.01431, 0.01570443, 0.01714744, 0.01878122, 0.02074801, 0.02319, 0.02620736, 0.02978248, 0.03388092, 0.03846824, 0.04351, 0.0489956, 0.0550226, 0.0617188, 0.069212, 0.07763, 0.08695811, 0.09717672, 0.1084063, 0.1207672, 0.13438, 0.1493582, 0.1653957, 0.1819831, 0.198611, 0.21477, 0.2301868, 0.2448797, 0.2587773, 0.2718079, 0.2839, 0.2949438, 0.3048965, 0.3137873, 0.3216454, 0.3285, 0.3343513, 0.3392101, 0.3431213, 0.3461296, 0.34828, 0.3495999, 0.3501474, 0.350013, 0.349287, 0.34806, 0.3463733, 0.3442624, 0.3418088, 0.3390941, 0.3362, 0.3331977, 0.3300411, 0.3266357, 0.3228868, 0.3187, 0.3140251, 0.308884, 0.3032904, 0.2972579, 0.2908, 0.2839701, 0.2767214, 0.2689178, 0.2604227, 0.2511, 0.2408475, 0.2298512, 0.2184072, 0.2068115, 0.19536, 0.1842136, 0.1733273, 0.1626881, 0.1522833, 0.1421, 0.1321786, 0.1225696, 0.1132752, 0.1042979, 0.09564, 0.08729955, 0.07930804, 0.07171776, 0.06458099, 0.05795001, 0.05186211, 0.04628152, 0.04115088, 0.03641283, 0.03201, 0.0279172, 0.0241444, 0.020687, 0.0175404, 0.0147, 0.01216179, 0.00991996, 0.00796724, 0.006296346, 0.0049, 0.003777173, 0.00294532, 0.00242488, 0.002236293, 0.0024, 0.00292552, 0.00383656, 0.00517484, 0.00698208, 0.0093, 0.01214949, 0.01553588, 0.01947752, 0.02399277, 0.0291, 0.03481485, 0.04112016, 0.04798504, 0.05537861, 0.06327, 0.07163501, 0.08046224, 0.08973996, 0.09945645, 0.1096, 0.1201674, 0.1311145, 0.1423679, 0.1538542, 0.1655, 0.1772571, 0.18914, 0.2011694, 0.2133658, 0.2257499, 0.2383209, 0.2510668, 0.2639922, 0.2771017, 0.2904, 0.3038912, 0.3175726, 0.3314384, 0.3454828, 0.3597, 0.3740839, 0.3886396, 0.4033784, 0.4183115, 0.4334499, 0.4487953, 0.464336, 0.480064, 0.4959713, 0.5120501, 0.5282959, 0.5446916, 0.5612094, 0.5778215, 0.5945, 0.6112209, 0.6279758, 0.6447602, 0.6615697, 0.6784, 0.6952392, 0.7120586, 0.7288284, 0.7455188, 0.7621, 0.7785432, 0.7948256, 0.8109264, 0.8268248, 0.8425, 0.8579325, 0.8730816, 0.8878944, 0.9023181, 0.9163, 0.9297995, 0.9427984, 0.9552776, 0.9672179, 0.9786, 0.9893856, 0.9995488, 1.0090892, 1.0180064, 1.0263, 1.0339827, 1.040986, 1.047188, 1.0524667, 1.0567, 1.0597944, 1.0617992, 1.0628068, 1.0629096, 1.0622, 1.0607352, 1.0584436, 1.0552244, 1.0509768, 1.0456, 1.0390369, 1.0313608, 1.0226662, 1.0130477, 1.0026, 0.9913675, 0.9793314, 0.9664916, 0.9528479, 0.9384, 0.923194, 0.907244, 0.890502, 0.87292, 0.8544499, 0.835084, 0.814946, 0.794186, 0.772954, 0.7514, 0.7295836, 0.7075888, 0.6856022, 0.6638104, 0.6424, 0.6215149, 0.6011138, 0.5811052, 0.5613977, 0.5419, 0.5225995, 0.5035464, 0.4847436, 0.4661939, 0.4479, 0.4298613, 0.412098, 0.394644, 0.3775333, 0.3608, 0.3444563, 0.3285168, 0.3130192, 0.2980011, 0.2835, 0.2695448, 0.2561184, 0.2431896, 0.2307272, 0.2187, 0.2070971, 0.1959232, 0.1851708, 0.1748323, 0.1649, 0.1553667, 0.14623, 0.13749, 0.1291467, 0.1212, 0.1136397, 0.106465, 0.09969044, 0.09333061, 0.0874, 0.08190096, 0.07680428, 0.07207712, 0.06768664, 0.0636, 0.05980685, 0.05628216, 0.05297104, 0.04981861, 0.04677, 0.04378405, 0.04087536, 0.03807264, 0.03540461, 0.0329, 0.03056419, 0.02838056, 0.02634484, 0.02445275, 0.0227, 0.02108429, 0.01959988, 0.01823732, 0.01698717, 0.01584, 0.01479064, 0.01383132, 0.01294868, 0.0121292, 0.01135916, 0.01062935, 0.009938846, 0.009288422, 0.008678854, 0.008110916, 0.007582388, 0.007088746, 0.006627313, 0.006195408, 0.005790346, 0.005409826, 0.005052583, 0.004717512, 0.004403507, 0.004109457, 0.003833913, 0.003575748, 0.003334342, 0.003109075, 0.002899327, 0.002704348, 0.00252302, 0.002354168, 0.002196616, 0.00204919, 0.00191096, 0.001781438, 0.00166011, 0.001546459, 0.001439971, 0.001340042, 0.001246275, 0.001158471, 0.00107643, 0.000999949, 0.000928736, 0.000862433, 0.00080075, 0.000743396, 0.000690079, 0.000640516, 0.000594502, 0.000551865, 0.000512429, 0.000476021, 0.000442454, 0.000411512, 0.000382981, 0.000356649, 0.000332301, 0.000309759, 0.000288887, 0.000269539, 0.000251568, 0.000234826, 0.000219171, 0.000204526, 0.000190841, 0.000178065, 0.000166151, 0.000155024, 0.000144622, 0.00013491, 0.000125852, 0.000117413, 0.000109552, 0.000102225, 9.53945E-05, 8.90239E-05, 8.30753E-05, 7.75127E-05, 7.2313E-05, 6.74578E-05, 6.29284E-05, 5.87065E-05, 5.47703E-05, 5.10992E-05, 4.76765E-05, 4.44857E-05, 4.15099E-05, 3.87332E-05, 3.6142E-05, 3.37235E-05, 3.14649E-05, 2.93533E-05, 2.73757E-05, 2.55243E-05, 2.37938E-05, 2.21787E-05, 2.06738E-05, 1.92723E-05, 1.79664E-05, 1.67499E-05, 1.56165E-05, 1.45598E-05, 1.35739E-05, 1.26544E-05, 1.17972E-05, 1.09984E-05, 1.0254E-05, 9.55965E-06, 8.91204E-06, 8.30836E-06, 7.74577E-06, 7.22146E-06, 6.73248E-06, 6.27642E-06, 5.8513E-06, 5.45512E-06, 5.08587E-06, 4.74147E-06, 4.42024E-06, 4.12078E-06, 3.84172E-06, 3.58165E-06, 3.33913E-06, 3.11295E-06, 2.90212E-06, 2.70565E-06, 2.52253E-06, 2.35173E-06, 2.19242E-06, 2.0439E-06, 1.9055E-06, 1.77651E-06, 1.65622E-06, 1.54402E-06, 1.43944E-06, 1.34198E-06, 1.25114E-06 }; public static readonly double[] CieXYZ31_Y_360_830_1nm = { 0.000003917, 4.39358E-06, 4.9296E-06, 5.53214E-06, 6.20825E-06, 0.000006965, 7.81322E-06, 8.76734E-06, 9.83984E-06, 1.10432E-05, 0.00001239, 1.38864E-05, 1.55573E-05, 1.7443E-05, 1.95838E-05, 0.00002202, 2.48397E-05, 2.80413E-05, 3.1531E-05, 3.52152E-05, 0.000039, 4.28264E-05, 4.69146E-05, 5.15896E-05, 5.71764E-05, 0.000064, 7.23442E-05, 8.22122E-05, 9.35082E-05, 0.000106136, 0.00012, 0.000134984, 0.000151492, 0.000170208, 0.000191816, 0.000217, 0.000246907, 0.00028124, 0.00031852, 0.000357267, 0.000396, 0.000433715, 0.000473024, 0.000517876, 0.000572219, 0.00064, 0.00072456, 0.0008255, 0.00094116, 0.00106988, 0.00121, 0.001362091, 0.001530752, 0.001720368, 0.001935323, 0.00218, 0.0024548, 0.002764, 0.0031178, 0.0035264, 0.004, 0.00454624, 0.00515932, 0.00582928, 0.00654616, 0.0073, 0.008086507, 0.00890872, 0.00976768, 0.01066443, 0.0116, 0.01257317, 0.01358272, 0.01462968, 0.01571509, 0.01684, 0.01800736, 0.01921448, 0.02045392, 0.02171824, 0.023, 0.02429461, 0.02561024, 0.02695857, 0.02835125, 0.0298, 0.03131083, 0.03288368, 0.03452112, 0.03622571, 0.038, 0.03984667, 0.041768, 0.043766, 0.04584267, 0.048, 0.05024368, 0.05257304, 0.05498056, 0.05745872, 0.06, 0.06260197, 0.06527752, 0.06804208, 0.07091109, 0.0739, 0.077016, 0.0802664, 0.0836668, 0.0872328, 0.09098, 0.09491755, 0.09904584, 0.1033674, 0.1078846, 0.1126, 0.117532, 0.1226744, 0.1279928, 0.1334528, 0.13902, 0.1446764, 0.1504693, 0.1564619, 0.1627177, 0.1693, 0.1762431, 0.1835581, 0.1912735, 0.199418, 0.20802, 0.2171199, 0.2267345, 0.2368571, 0.2474812, 0.2586, 0.2701849, 0.2822939, 0.2950505, 0.308578, 0.323, 0.3384021, 0.3546858, 0.3716986, 0.3892875, 0.4073, 0.4256299, 0.4443096, 0.4633944, 0.4829395, 0.503, 0.5235693, 0.544512, 0.56569, 0.5869653, 0.6082, 0.6293456, 0.6503068, 0.6708752, 0.6908424, 0.71, 0.7281852, 0.7454636, 0.7619694, 0.7778368, 0.7932, 0.8081104, 0.8224962, 0.8363068, 0.8494916, 0.862, 0.8738108, 0.8849624, 0.8954936, 0.9054432, 0.9148501, 0.9237348, 0.9320924, 0.9399226, 0.9472252, 0.954, 0.9602561, 0.9660074, 0.9712606, 0.9760225, 0.9803, 0.9840924, 0.9874182, 0.9903128, 0.9928116, 0.9949501, 0.9967108, 0.9980983, 0.999112, 0.9997482, 1, 0.9998567, 0.9993046, 0.9983255, 0.9968987, 0.995, 0.9926005, 0.9897426, 0.9864444, 0.9827241, 0.9786, 0.9740837, 0.9691712, 0.9638568, 0.9581349, 0.952, 0.9454504, 0.9384992, 0.9311628, 0.9234576, 0.9154, 0.9070064, 0.8982772, 0.8892048, 0.8797816, 0.87, 0.8598613, 0.849392, 0.838622, 0.8275813, 0.8163, 0.8047947, 0.793082, 0.781192, 0.7691547, 0.757, 0.7447541, 0.7324224, 0.7200036, 0.7074965, 0.6949, 0.6822192, 0.6694716, 0.6566744, 0.6438448, 0.631, 0.6181555, 0.6053144, 0.5924756, 0.5796379, 0.5668, 0.5539611, 0.5411372, 0.5283528, 0.5156323, 0.503, 0.4904688, 0.4780304, 0.4656776, 0.4534032, 0.4412, 0.42908, 0.417036, 0.405032, 0.393032, 0.381, 0.3689184, 0.3568272, 0.3447768, 0.3328176, 0.321, 0.3093381, 0.2978504, 0.2865936, 0.2756245, 0.265, 0.2547632, 0.2448896, 0.2353344, 0.2260528, 0.217, 0.2081616, 0.1995488, 0.1911552, 0.1829744, 0.175, 0.1672235, 0.1596464, 0.1522776, 0.1451259, 0.1382, 0.1315003, 0.1250248, 0.1187792, 0.1127691, 0.107, 0.1014762, 0.09618864, 0.09112296, 0.08626485, 0.0816, 0.07712064, 0.07282552, 0.06871008, 0.06476976, 0.061, 0.05739621, 0.05395504, 0.05067376, 0.04754965, 0.04458, 0.04175872, 0.03908496, 0.03656384, 0.03420048, 0.032, 0.02996261, 0.02807664, 0.02632936, 0.02470805, 0.0232, 0.02180077, 0.02050112, 0.01928108, 0.01812069, 0.017, 0.01590379, 0.01483718, 0.01381068, 0.01283478, 0.01192, 0.01106831, 0.01027339, 0.009533311, 0.008846157, 0.00821, 0.007623781, 0.007085424, 0.006591476, 0.006138485, 0.005723, 0.005343059, 0.004995796, 0.004676404, 0.004380075, 0.004102, 0.003838453, 0.003589099, 0.003354219, 0.003134093, 0.002929, 0.002738139, 0.002559876, 0.002393244, 0.002237275, 0.002091, 0.001953587, 0.00182458, 0.00170358, 0.001590187, 0.001484, 0.001384496, 0.001291268, 0.001204092, 0.001122744, 0.001047, 0.00097659, 0.000911109, 0.000850133, 0.000793238, 0.00074, 0.000690083, 0.00064331, 0.000599496, 0.000558455, 0.00052, 0.000483914, 0.000450053, 0.000418345, 0.000388718, 0.0003611, 0.000335384, 0.00031144, 0.000289166, 0.000268454, 0.0002492, 0.000231302, 0.000214686, 0.000199288, 0.000185048, 0.0001719, 0.000159778, 0.000148604, 0.000138302, 0.000128793, 0.00012, 0.00011186, 0.000104322, 9.73356E-05, 9.08459E-05, 0.0000848, 7.91467E-05, 0.000073858, 0.000068916, 6.43027E-05, 0.00006, 5.59819E-05, 5.22256E-05, 4.87184E-05, 4.54475E-05, 0.0000424, 3.9561E-05, 3.69151E-05, 3.44487E-05, 3.21482E-05, 0.00003, 2.79913E-05, 2.61136E-05, 2.43602E-05, 2.27246E-05, 0.0000212, 1.97786E-05, 1.84529E-05, 1.72169E-05, 1.60646E-05, 0.00001499, 1.39873E-05, 1.30516E-05, 1.21782E-05, 1.13625E-05, 0.0000106, 9.88588E-06, 9.2173E-06, 8.59236E-06, 8.00913E-06, 7.4657E-06, 6.95957E-06, 6.488E-06, 6.0487E-06, 5.6394E-06, 5.2578E-06, 4.90177E-06, 4.56972E-06, 4.26019E-06, 3.97174E-06, 3.7029E-06, 3.45216E-06, 3.2183E-06, 3.0003E-06, 2.79714E-06, 2.6078E-06, 2.43122E-06, 2.26653E-06, 2.11301E-06, 1.96994E-06, 1.8366E-06, 1.71223E-06, 1.59623E-06, 1.48809E-06, 1.38731E-06, 1.2934E-06, 1.20582E-06, 1.12414E-06, 1.04801E-06, 9.77058E-07, 9.1093E-07, 8.49251E-07, 7.91721E-07, 7.3809E-07, 6.8811E-07, 6.4153E-07, 5.9809E-07, 5.57575E-07, 5.19808E-07, 4.84612E-07, 4.5181E-07 }; public static readonly double[] CieXYZ31_Z_360_830_1nm = { 0.0006061, 0.000680879, 0.000765146, 0.000860012, 0.000966593, 0.001086, 0.001220586, 0.001372729, 0.001543579, 0.001734286, 0.001946, 0.002177777, 0.002435809, 0.002731953, 0.003078064, 0.003486, 0.003975227, 0.00454088, 0.00515832, 0.005802907, 0.006450001, 0.007083216, 0.007745488, 0.008501152, 0.009414544, 0.01054999, 0.0119658, 0.01365587, 0.01558805, 0.01773015, 0.02005001, 0.02251136, 0.02520288, 0.02827972, 0.03189704, 0.03621, 0.04143771, 0.04750372, 0.05411988, 0.06099803, 0.06785001, 0.07448632, 0.08136156, 0.08915364, 0.09854048, 0.1102, 0.1246133, 0.1417017, 0.1613035, 0.1832568, 0.2074, 0.2336921, 0.2626114, 0.2947746, 0.3307985, 0.3713, 0.4162091, 0.4654642, 0.5196948, 0.5795303, 0.6456, 0.7184838, 0.7967133, 0.8778459, 0.959439, 1.0390501, 1.1153673, 1.1884971, 1.2581233, 1.3239296, 1.3856, 1.4426352, 1.4948035, 1.5421903, 1.5848807, 1.62296, 1.6564048, 1.6852959, 1.7098745, 1.7303821, 1.74706, 1.7600446, 1.7696233, 1.7762637, 1.7804334, 1.7826, 1.7829682, 1.7816998, 1.7791982, 1.7758671, 1.77211, 1.7682589, 1.764039, 1.7589438, 1.7524663, 1.7441, 1.7335595, 1.7208581, 1.7059369, 1.6887372, 1.6692, 1.6475287, 1.6234127, 1.5960223, 1.564528, 1.5281, 1.4861114, 1.4395215, 1.3898799, 1.3387362, 1.28764, 1.2374223, 1.1878243, 1.1387611, 1.090148, 1.0419, 0.9941976, 0.9473473, 0.9014531, 0.8566193, 0.8129501, 0.7705173, 0.7294448, 0.6899136, 0.6521049, 0.6162, 0.5823286, 0.5504162, 0.5203376, 0.4919673, 0.46518, 0.4399246, 0.4161836, 0.3938822, 0.3729459, 0.3533, 0.3348578, 0.3175521, 0.3013375, 0.2861686, 0.272, 0.2588171, 0.2464838, 0.2347718, 0.2234533, 0.2123, 0.2011692, 0.1901196, 0.1792254, 0.1685608, 0.1582, 0.1481383, 0.1383758, 0.1289942, 0.1200751, 0.1117, 0.1039048, 0.09666748, 0.08998272, 0.08384531, 0.07824999, 0.07320899, 0.06867816, 0.06456784, 0.06078835, 0.05725001, 0.05390435, 0.05074664, 0.04775276, 0.04489859, 0.04216, 0.03950728, 0.03693564, 0.03445836, 0.03208872, 0.02984, 0.02771181, 0.02569444, 0.02378716, 0.02198925, 0.0203, 0.01871805, 0.01724036, 0.01586364, 0.01458461, 0.0134, 0.01230723, 0.01130188, 0.01037792, 0.009529306, 0.008749999, 0.0080352, 0.0073816, 0.0067854, 0.0062428, 0.005749999, 0.0053036, 0.0048998, 0.0045342, 0.0042024, 0.0039, 0.0036232, 0.0033706, 0.0031414, 0.0029348, 0.002749999, 0.0025852, 0.0024386, 0.0023094, 0.0021968, 0.0021, 0.002017733, 0.0019482, 0.0018898, 0.001840933, 0.0018, 0.001766267, 0.0017378, 0.0017112, 0.001683067, 0.001650001, 0.001610133, 0.0015644, 0.0015136, 0.001458533, 0.0014, 0.001336667, 0.00127, 0.001205, 0.001146667, 0.0011, 0.0010688, 0.0010494, 0.0010356, 0.0010212, 0.001, 0.00096864, 0.00092992, 0.00088688, 0.00084256, 0.0008, 0.00076096, 0.00072368, 0.00068592, 0.00064544, 0.0006, 0.000547867, 0.0004916, 0.0004354, 0.000383467, 0.00034, 0.000307253, 0.00028316, 0.00026544, 0.000251813, 0.00024, 0.000229547, 0.00022064, 0.00021196, 0.000202187, 0.00019, 0.000174213, 0.00015564, 0.00013596, 0.000116853, 0.0001, 8.61333E-05, 0.0000746, 0.000065, 5.69333E-05, 5E-05, 0.00004416, 0.00003948, 0.00003572, 0.00003264, 0.00003, 2.76533E-05, 0.00002556, 0.00002364, 2.18133E-05, 0.00002, 1.81333E-05, 0.0000162, 0.0000142, 1.21333E-05, 0.00001, 7.73333E-06, 0.0000054, 0.0000032, 1.33333E-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #endregion #region CIE Illuminant A Spectral Distribution 300-830nm in 1nm steps public static readonly double[] CieIlluminantA_300_830_1nm = { 0.930483, 0.967643, 1.00597, 1.04549, 1.08623, 1.12821, 1.17147, 1.21602, 1.26188, 1.3091, 1.35769, 1.40768, 1.4591, 1.51198, 1.56633, 1.62219, 1.67959, 1.73855, 1.7991, 1.86127, 1.92508, 1.99057, 2.05776, 2.12667, 2.19734, 2.2698, 2.34406, 2.42017, 2.49814, 2.57801, 2.65981, 2.74355, 2.82928, 2.91701, 3.00678, 3.09861, 3.19253, 3.28857, 3.38676, 3.48712, 3.58968, 3.69447, 3.80152, 3.91085, 4.0225, 4.13648, 4.25282, 4.37156, 4.49272, 4.61631, 4.74238, 4.87095, 5.00204, 5.13568, 5.27189, 5.4107, 5.55213, 5.69622, 5.84298, 5.99244, 6.14462, 6.29955, 6.45724, 6.61774, 6.78105, 6.9472, 7.11621, 7.28811, 7.46292, 7.64066, 7.82135, 8.00501, 8.19167, 8.38134, 8.57404, 8.7698, 8.96864, 9.17056, 9.37561, 9.58378, 9.7951, 10.0096, 10.2273, 10.4481, 10.6722, 10.8996, 11.1302, 11.364, 11.6012, 11.8416, 12.0853, 12.3324, 12.5828, 12.8366, 13.0938, 13.3543, 13.6182, 13.8855, 14.1563, 14.4304, 14.708, 14.9891, 15.2736, 15.5616, 15.853, 16.148, 16.4464, 16.7484, 17.0538, 17.3628, 17.6753, 17.9913, 18.3108, 18.6339, 18.9605, 19.2907, 19.6244, 19.9617, 20.3026, 20.647, 20.995, 21.3465, 21.7016, 22.0603, 22.4225, 22.7883, 23.1577, 23.5307, 23.9072, 24.2873, 24.6709, 25.0581, 25.4489, 25.8432, 26.2411, 26.6425, 27.0475, 27.456, 27.8681, 28.2836, 28.7027, 29.1253, 29.5515, 29.9811, 30.4142, 30.8508, 31.2909, 31.7345, 32.1815, 32.632, 33.0859, 33.5432, 34.004, 34.4682, 34.9358, 35.4068, 35.8811, 36.3588, 36.8399, 37.3243, 37.8121, 38.3031, 38.7975, 39.2951, 39.796, 40.3002, 40.8076, 41.3182, 41.832, 42.3491, 42.8693, 43.3926, 43.9192, 44.4488, 44.9816, 45.5174, 46.0563, 46.5983, 47.1433, 47.6913, 48.2423, 48.7963, 49.3533, 49.9132, 50.476, 51.0418, 51.6104, 52.1818, 52.7561, 53.3332, 53.9132, 54.4958, 55.0813, 55.6694, 56.2603, 56.8539, 57.4501, 58.0489, 58.6504, 59.2545, 59.8611, 60.4703, 61.082, 61.6962, 62.3128, 62.932, 63.5535, 64.1775, 64.8038, 65.4325, 66.0635, 66.6968, 67.3324, 67.9702, 68.6102, 69.2525, 69.8969, 70.5435, 71.1922, 71.843, 72.4959, 73.1508, 73.8077, 74.4666, 75.1275, 75.7903, 76.4551, 77.1217, 77.7902, 78.4605, 79.1326, 79.8065, 80.4821, 81.1595, 81.8386, 82.5193, 83.2017, 83.8856, 84.5712, 85.2584, 85.947, 86.6372, 87.3288, 88.0219, 88.7165, 89.4124, 90.1097, 90.8083, 91.5082, 92.2095, 92.912, 93.6157, 94.3206, 95.0267, 95.7339, 96.4423, 97.1518, 97.8623, 98.5739, 99.2864, 100, 100.715, 101.43, 102.146, 102.864, 103.582, 104.301, 105.02, 105.741, 106.462, 107.184, 107.906, 108.63, 109.354, 110.078, 110.803, 111.529, 112.255, 112.982, 113.709, 114.436, 115.164, 115.893, 116.622, 117.351, 118.08, 118.81, 119.54, 120.27, 121.001, 121.731, 122.462, 123.193, 123.924, 124.655, 125.386, 126.118, 126.849, 127.58, 128.312, 129.043, 129.774, 130.505, 131.236, 131.966, 132.697, 133.427, 134.157, 134.887, 135.617, 136.346, 137.075, 137.804, 138.532, 139.26, 139.988, 140.715, 141.441, 142.167, 142.893, 143.618, 144.343, 145.067, 145.79, 146.513, 147.235, 147.957, 148.678, 149.398, 150.117, 150.836, 151.554, 152.271, 152.988, 153.704, 154.418, 155.132, 155.845, 156.558, 157.269, 157.979, 158.689, 159.397, 160.104, 160.811, 161.516, 162.221, 162.924, 163.626, 164.327, 165.028, 165.726, 166.424, 167.121, 167.816, 168.51, 169.203, 169.895, 170.586, 171.275, 171.963, 172.65, 173.335, 174.019, 174.702, 175.383, 176.063, 176.741, 177.419, 178.094, 178.769, 179.441, 180.113, 180.783, 181.451, 182.118, 182.783, 183.447, 184.109, 184.77, 185.429, 186.087, 186.743, 187.397, 188.05, 188.701, 189.35, 189.998, 190.644, 191.288, 191.931, 192.572, 193.211, 193.849, 194.484, 195.118, 195.75, 196.381, 197.009, 197.636, 198.261, 198.884, 199.506, 200.125, 200.743, 201.359, 201.972, 202.584, 203.195, 203.803, 204.409, 205.013, 205.616, 206.216, 206.815, 207.411, 208.006, 208.599, 209.189, 209.778, 210.365, 210.949, 211.532, 212.112, 212.691, 213.268, 213.842, 214.415, 214.985, 215.553, 216.12, 216.684, 217.246, 217.806, 218.364, 218.92, 219.473, 220.025, 220.574, 221.122, 221.667, 222.21, 222.751, 223.29, 223.826, 224.361, 224.893, 225.423, 225.951, 226.477, 227, 227.522, 228.041, 228.558, 229.073, 229.585, 230.096, 230.604, 231.11, 231.614, 232.115, 232.615, 233.112, 233.606, 234.099, 234.589, 235.078, 235.564, 236.047, 236.529, 237.008, 237.485, 237.959, 238.432, 238.902, 239.37, 239.836, 240.299, 240.76, 241.219, 241.675, 242.13, 242.582, 243.031, 243.479, 243.924, 244.367, 244.808, 245.246, 245.682, 246.116, 246.548, 246.977, 247.404, 247.829, 248.251, 248.671, 249.089, 249.505, 249.918, 250.329, 250.738, 251.144, 251.548, 251.95, 252.35, 252.747, 253.142, 253.535, 253.925, 254.314, 254.7, 255.083, 255.465, 255.844, 256.221, 256.595, 256.968, 257.338, 257.706, 258.071, 258.434, 258.795, 259.154, 259.511, 259.865, 260.217, 260.567, 260.914, 261.259, 261.602 }; #endregion #region CIE Illuminant D65 Spectral Distribution 300-830nm in 1nm steps public static readonly double[] CieIlluminantD65_300_830_1nm = { 0.0341, 0.36014, 0.68618, 1.01222, 1.33826, 1.6643, 1.99034, 2.31638, 2.64242, 2.96846, 3.2945, 4.98865, 6.6828, 8.37695, 10.0711, 11.7652, 13.4594, 15.1535, 16.8477, 18.5418, 20.236, 21.9177, 23.5995, 25.2812, 26.963, 28.6447, 30.3265, 32.0082, 33.69, 35.3717, 37.0535, 37.343, 37.6326, 37.9221, 38.2116, 38.5011, 38.7907, 39.0802, 39.3697, 39.6593, 39.9488, 40.4451, 40.9414, 41.4377, 41.934, 42.4302, 42.9265, 43.4228, 43.9191, 44.4154, 44.9117, 45.0844, 45.257, 45.4297, 45.6023, 45.775, 45.9477, 46.1203, 46.293, 46.4656, 46.6383, 47.1834, 47.7285, 48.2735, 48.8186, 49.3637, 49.9088, 50.4539, 50.9989, 51.544, 52.0891, 51.8777, 51.6664, 51.455, 51.2437, 51.0323, 50.8209, 50.6096, 50.3982, 50.1869, 49.9755, 50.4428, 50.91, 51.3773, 51.8446, 52.3118, 52.7791, 53.2464, 53.7137, 54.1809, 54.6482, 57.4589, 60.2695, 63.0802, 65.8909, 68.7015, 71.5122, 74.3229, 77.1336, 79.9442, 82.7549, 83.628, 84.5011, 85.3742, 86.2473, 87.1204, 87.9936, 88.8667, 89.7398, 90.6129, 91.486, 91.6806, 91.8752, 92.0697, 92.2643, 92.4589, 92.6535, 92.8481, 93.0426, 93.2372, 93.4318, 92.7568, 92.0819, 91.4069, 90.732, 90.057, 89.3821, 88.7071, 88.0322, 87.3572, 86.6823, 88.5006, 90.3188, 92.1371, 93.9554, 95.7736, 97.5919, 99.4102, 101.228, 103.047, 104.865, 106.079, 107.294, 108.508, 109.722, 110.936, 112.151, 113.365, 114.579, 115.794, 117.008, 117.088, 117.169, 117.249, 117.33, 117.41, 117.49, 117.571, 117.651, 117.732, 117.812, 117.517, 117.222, 116.927, 116.632, 116.336, 116.041, 115.746, 115.451, 115.156, 114.861, 114.967, 115.073, 115.18, 115.286, 115.392, 115.498, 115.604, 115.711, 115.817, 115.923, 115.212, 114.501, 113.789, 113.078, 112.367, 111.656, 110.945, 110.233, 109.522, 108.811, 108.865, 108.92, 108.974, 109.028, 109.082, 109.137, 109.191, 109.245, 109.3, 109.354, 109.199, 109.044, 108.888, 108.733, 108.578, 108.423, 108.268, 108.112, 107.957, 107.802, 107.501, 107.2, 106.898, 106.597, 106.296, 105.995, 105.694, 105.392, 105.091, 104.79, 105.08, 105.37, 105.66, 105.95, 106.239, 106.529, 106.819, 107.109, 107.399, 107.689, 107.361, 107.032, 106.704, 106.375, 106.047, 105.719, 105.39, 105.062, 104.733, 104.405, 104.369, 104.333, 104.297, 104.261, 104.225, 104.19, 104.154, 104.118, 104.082, 104.046, 103.641, 103.237, 102.832, 102.428, 102.023, 101.618, 101.214, 100.809, 100.405, 100, 99.6334, 99.2668, 98.9003, 98.5337, 98.1671, 97.8005, 97.4339, 97.0674, 96.7008, 96.3342, 96.2796, 96.225, 96.1703, 96.1157, 96.0611, 96.0065, 95.9519, 95.8972, 95.8426, 95.788, 95.0778, 94.3675, 93.6573, 92.947, 92.2368, 91.5266, 90.8163, 90.1061, 89.3958, 88.6856, 88.8177, 88.9497, 89.0818, 89.2138, 89.3459, 89.478, 89.61, 89.7421, 89.8741, 90.0062, 89.9655, 89.9248, 89.8841, 89.8434, 89.8026, 89.7619, 89.7212, 89.6805, 89.6398, 89.5991, 89.4091, 89.219, 89.029, 88.8389, 88.6489, 88.4589, 88.2688, 88.0788, 87.8887, 87.6987, 87.2577, 86.8167, 86.3757, 85.9347, 85.4936, 85.0526, 84.6116, 84.1706, 83.7296, 83.2886, 83.3297, 83.3707, 83.4118, 83.4528, 83.4939, 83.535, 83.576, 83.6171, 83.6581, 83.6992, 83.332, 82.9647, 82.5975, 82.2302, 81.863, 81.4958, 81.1285, 80.7613, 80.394, 80.0268, 80.0456, 80.0644, 80.0831, 80.1019, 80.1207, 80.1395, 80.1583, 80.177, 80.1958, 80.2146, 80.4209, 80.6272, 80.8336, 81.0399, 81.2462, 81.4525, 81.6588, 81.8652, 82.0715, 82.2778, 81.8784, 81.4791, 81.0797, 80.6804, 80.281, 79.8816, 79.4823, 79.0829, 78.6836, 78.2842, 77.4279, 76.5716, 75.7153, 74.859, 74.0027, 73.1465, 72.2902, 71.4339, 70.5776, 69.7213, 69.9101, 70.0989, 70.2876, 70.4764, 70.6652, 70.854, 71.0428, 71.2315, 71.4203, 71.6091, 71.8831, 72.1571, 72.4311, 72.7051, 72.979, 73.253, 73.527, 73.801, 74.075, 74.349, 73.0745, 71.8, 70.5255, 69.251, 67.9765, 66.702, 65.4275, 64.153, 62.8785, 61.604, 62.4322, 63.2603, 64.0885, 64.9166, 65.7448, 66.573, 67.4011, 68.2293, 69.0574, 69.8856, 70.4057, 70.9259, 71.446, 71.9662, 72.4863, 73.0064, 73.5266, 74.0467, 74.5669, 75.087, 73.9376, 72.7881, 71.6387, 70.4893, 69.3398, 68.1904, 67.041, 65.8916, 64.7421, 63.5927, 61.8752, 60.1578, 58.4403, 56.7229, 55.0054, 53.288, 51.5705, 49.8531, 48.1356, 46.4182, 48.4569, 50.4956, 52.5344, 54.5731, 56.6118, 58.6505, 60.6892, 62.728, 64.7667, 66.8054, 66.4631, 66.1209, 65.7786, 65.4364, 65.0941, 64.7518, 64.4096, 64.0673, 63.7251, 63.3828, 63.4749, 63.567, 63.6592, 63.7513, 63.8434, 63.9355, 64.0276, 64.1198, 64.2119, 64.304, 63.8188, 63.3336, 62.8484, 62.3632, 61.8779, 61.3927, 60.9075, 60.4223, 59.9371, 59.4519, 58.7026, 57.9533, 57.204, 56.4547, 55.7054, 54.9562, 54.2069, 53.4576, 52.7083, 51.959, 52.5072, 53.0553, 53.6035, 54.1516, 54.6998, 55.248, 55.7961, 56.3443, 56.8924, 57.4406, 57.7278, 58.015, 58.3022, 58.5894, 58.8765, 59.1637, 59.4509, 59.7381, 60.0253, 60.3125 }; #endregion #region Preetham Sky Spectrum to XYZ Conversion /// <summary> /// sun color spectrum S0 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS0_380_780_10nm = { 63.4, 65.8, 94.8, 104.8, 105.9, 96.8, 113.9, 125.6, 125.5, 121.3, 121.3, 113.5, 113.1, 110.8, 106.5, 108.8, 105.3, 104.4, 100.0, 96.0, 95.1, 89.1, 90.5, 90.3, 88.4, 84.0, 85.1, 81.9, 82.6, 84.9, 81.3, 71.9, 74.3, 76.4, 63.3, 71.7, 77.0, 65.2, 47.7, 68.6, 65.0 }; /// <summary> /// sun color spectrum S1 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS1_380_780_10nm = { 38.5, 35.0, 43.4, 46.3, 43.9, 37.1, 36.7, 35.9, 32.6, 27.9, 24.3, 20.1, 16.2, 13.2, 8.6, 6.1, 4.2, 1.9, 0.0, -1.6, -3.5, -3.5, -5.8, -7.2, -8.6, -9.5, -10.9, -10.7, -12.0, -14.0, -13.6, -12.0, -13.3, -12.9, -10.6, -11.6, -12.2, -10.2, -7.8, -11.2, -10.4 }; /// <summary> /// sun color spectrum S2 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS2_380_780_10nm = { 3.0, 1.2, -1.1, -0.5, -0.7, -1.2, -2.6, -2.9, -2.8, -2.6, -2.6, -1.8, -1.5, -1.3, -1.2, -1.0, -0.5, -0.3, 0.0, 0.2, 0.5, 2.1, 3.2, 4.1, 4.7, 5.1, 6.7, 7.3, 8.6, 9.8, 10.2, 8.3, 9.6, 8.5, 7.0, 7.6, 8.0, 6.7, 5.2, 7.4, 6.8 }; /// <summary> /// CIE XYZ standard observer sensitivity function X in 10mn steps. /// </summary> public static readonly double[] Ciexyz31X_380_780_10nm = { 0.001368000000, 0.004243000000, 0.014310000000, 0.043510000000, 0.134380000000, 0.283900000000, 0.348280000000, 0.336200000000, 0.290800000000, 0.195360000000, 0.095640000000, 0.032010000000, 0.004900000000, 0.009300000000, 0.063270000000, 0.165500000000, 0.290400000000, 0.433449900000, 0.594500000000, 0.762100000000, 0.916300000000, 1.026300000000, 1.062200000000, 1.002600000000, 0.854449900000, 0.642400000000, 0.447900000000, 0.283500000000, 0.164900000000, 0.087400000000, 0.046770000000, 0.022700000000, 0.011359160000, 0.005790346000, 0.002899327000, 0.001439971000, 0.000690078600, 0.000332301100, 0.000166150500, 0.000083075270, 0.000041509940 }; /// <summary> /// CIE XYZ standard observer sensitivity function Y in 10mn steps. /// </summary> public static readonly double[] Ciexyz31Y_380_780_10nm = { 0.000039000000, 0.000120000000, 0.000396000000, 0.001210000000, 0.004000000000, 0.011600000000, 0.023000000000, 0.038000000000, 0.060000000000, 0.090980000000, 0.139020000000, 0.208020000000, 0.323000000000, 0.503000000000, 0.710000000000, 0.862000000000, 0.954000000000, 0.994950100000, 0.995000000000, 0.952000000000, 0.870000000000, 0.757000000000, 0.631000000000, 0.503000000000, 0.381000000000, 0.265000000000, 0.175000000000, 0.107000000000, 0.061000000000, 0.032000000000, 0.017000000000, 0.008210000000, 0.004102000000, 0.002091000000, 0.001047000000, 0.000520000000, 0.000249200000, 0.000120000000, 0.000060000000, 0.000030000000, 0.000014990000 }; /// <summary> /// CIE XYZ standard observer sensitivity function Z in 10mn steps. /// </summary> public static readonly double[] Ciexyz31Z_380_780_10nm = { 0.006450001000, 0.020050010000, 0.067850010000, 0.207400000000, 0.645600000000, 1.385600000000, 1.747060000000, 1.772110000000, 1.669200000000, 1.287640000000, 0.812950100000, 0.465180000000, 0.272000000000, 0.158200000000, 0.078249990000, 0.042160000000, 0.020300000000, 0.008749999000, 0.003900000000, 0.002100000000, 0.001650001000, 0.001100000000, 0.000800000000, 0.000340000000, 0.000190000000, 0.000049999990, 0.000020000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000 }; static M33d CreateConversionMatrix() { // for spectral to xyz conversion see: http://www.brucelindbloom.com/index.html?Eqn_Spect_to_XYZ.html var specS0Vec = new Vector<double>(SpecS0_380_780_10nm); var specS1Vec = new Vector<double>(SpecS1_380_780_10nm); var specS2Vec = new Vector<double>(SpecS2_380_780_10nm); var cieXVec = new Vector<double>(Ciexyz31X_380_780_10nm); var cieYVec = new Vector<double>(Ciexyz31Y_380_780_10nm); var cieZVec = new Vector<double>(Ciexyz31Z_380_780_10nm); var specM = new M33d ( cieXVec.DotProduct(specS0Vec), cieXVec.DotProduct(specS1Vec), cieXVec.DotProduct(specS2Vec), cieYVec.DotProduct(specS0Vec), cieYVec.DotProduct(specS1Vec), cieYVec.DotProduct(specS2Vec), cieZVec.DotProduct(specS0Vec), cieZVec.DotProduct(specS1Vec), cieZVec.DotProduct(specS2Vec) ); var cieN = 1.0 / cieYVec.Data.Sum(); // cie response curve integral normalization // sun spectral radiance (S0, S1, S2) is expressed in micro-meters => // convert to wavelengthes in nm (unit of color matching functions) -> scale by 1/1000 // the cie response functions are in 10nm steps -> scale by 10 var specN = 1.0 / 1000 * 10; // spectrum unit converions (1 micro meter to 10 nano meter) var norm = cieN * specN; // normalization of color space conversion matrix return specM * norm; } /// <summary> /// conversion matrix from sun color spectrum in (S0, S1, S2) to CIE XYZ color space /// </summary> public static readonly M33d SpecM = CreateConversionMatrix(); #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System.Text; using System; using NPOI.Util; using System.Globalization; /** * NOTE: Comment Associated with a Cell (1Ch) * * @author Yegor Kozlov */ public class NoteRecord : StandardRecord { public static readonly NoteRecord[] EMPTY_ARRAY = { }; public const short sid = 0x1C; /** * Flag indicating that the comment Is hidden (default) */ public const short NOTE_HIDDEN = 0x0; /** * Flag indicating that the comment Is visible */ public const short NOTE_VISIBLE = 0x2; private int field_1_row; private int field_2_col; private short field_3_flags; private int field_4_shapeid; private bool field_5_hasMultibyte; private String field_6_author; private const Byte DEFAULT_PADDING = (byte)0; /** * Saves padding byte value to reduce delta during round-trip serialization.<br/> * * The documentation is not clear about how padding should work. In any case * Excel(2007) does something different. */ private Byte? field_7_padding; /** * Construct a new <c>NoteRecord</c> and * Fill its data with the default values */ public NoteRecord() { field_6_author = ""; field_3_flags = 0; field_7_padding = DEFAULT_PADDING; // seems to be always present regardless of author text } /** * Constructs a <c>NoteRecord</c> and Fills its fields * from the supplied <c>RecordInputStream</c>. * * @param in the stream to Read from */ public NoteRecord(RecordInputStream in1) { field_1_row = in1.ReadShort(); field_2_col = in1.ReadUShort(); field_3_flags = in1.ReadShort(); field_4_shapeid = in1.ReadUShort(); int length = in1.ReadShort(); field_5_hasMultibyte = in1.ReadByte() != 0x00; if (field_5_hasMultibyte) { field_6_author = StringUtil.ReadUnicodeLE(in1, length); } else { field_6_author = StringUtil.ReadCompressedUnicode(in1, length); } if (in1.Available() == 1) { field_7_padding = (byte)in1.ReadByte(); } } /** * @return id of this record. */ public override short Sid { get { return sid; } } /** * Serialize the record data into the supplied array of bytes * * @param offset offset in the <c>data</c> * @param data the data to Serialize into * * @return size of the record */ public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_row); out1.WriteShort(field_2_col); out1.WriteShort(field_3_flags); out1.WriteShort(field_4_shapeid); out1.WriteShort(field_6_author.Length); out1.WriteByte(field_5_hasMultibyte ? 0x01 : 0x00); if (field_5_hasMultibyte) { StringUtil.PutUnicodeLE(field_6_author, out1); } else { StringUtil.PutCompressedUnicode(field_6_author, out1); } if (field_7_padding != null) { out1.WriteByte(Convert.ToInt32(field_7_padding, CultureInfo.InvariantCulture)); } } /** * Size of record */ protected override int DataSize { get { return 11 // 5 shorts + 1 byte + field_6_author.Length * (field_5_hasMultibyte ? 2 : 1) + (field_7_padding == null ? 0 : 1); } } /** * Convert this record to string. * Used by BiffViewer and other utulities. */ public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[NOTE]\n"); buffer.Append(" .recordid = 0x" + StringUtil.ToHexString(Sid) + ", size = " + RecordSize + "\n"); buffer.Append(" .row = " + field_1_row + "\n"); buffer.Append(" .col = " + field_2_col + "\n"); buffer.Append(" .flags = " + field_3_flags + "\n"); buffer.Append(" .shapeid = " + field_4_shapeid + "\n"); buffer.Append(" .author = " + field_6_author + "\n"); buffer.Append("[/NOTE]\n"); return buffer.ToString(); } /** * Return the row that Contains the comment * * @return the row that Contains the comment */ public int Row { get{return field_1_row;} set{ field_1_row = value;} } /** * Return the column that Contains the comment * * @return the column that Contains the comment */ public int Column { get { return field_2_col; } set { field_2_col = value; } } /** * Options flags. * * @return the options flag * @see #NOTE_VISIBLE * @see #NOTE_HIDDEN */ public short Flags { get { return field_3_flags; } set { field_3_flags = value; } } /** * Object id for OBJ record that Contains the comment */ public int ShapeId { get { return field_4_shapeid; } set { field_4_shapeid = value; } } /** * Name of the original comment author * * @return the name of the original author of the comment */ public String Author { get { return field_6_author; } set { field_6_author = value; field_5_hasMultibyte = StringUtil.HasMultibyte(value); } } /** * For unit testing only! */ internal bool AuthorIsMultibyte { get { return field_5_hasMultibyte; } } public override Object Clone() { NoteRecord rec = new NoteRecord(); rec.field_1_row = field_1_row; rec.field_2_col = field_2_col; rec.field_3_flags = field_3_flags; rec.field_4_shapeid = field_4_shapeid; rec.field_6_author = field_6_author; return rec; } } }
// 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.Xml.Linq { public static partial class Extensions { public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XNode { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static System.Collections.Generic.IEnumerable<T> InDocumentOrder<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { return default(System.Collections.Generic.IEnumerable<T>); } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public static void Remove(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> source) { } public static void Remove<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { } } [System.FlagsAttribute] public enum LoadOptions { None = 0, PreserveWhitespace = 1, SetBaseUri = 2, SetLineInfo = 4, } [System.FlagsAttribute] public enum ReaderOptions { None = 0, OmitDuplicateNamespaces = 1, } [System.FlagsAttribute] public enum SaveOptions { DisableFormatting = 1, None = 0, OmitDuplicateNamespaces = 2, } public partial class XAttribute : System.Xml.Linq.XObject { public XAttribute(System.Xml.Linq.XAttribute other) { } public XAttribute(System.Xml.Linq.XName name, object value) { } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> EmptySequence { get { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>); } } public bool IsNamespaceDeclaration { get { return default(bool); } } public System.Xml.Linq.XName Name { get { return default(System.Xml.Linq.XName); } } public System.Xml.Linq.XAttribute NextAttribute { get { return default(System.Xml.Linq.XAttribute); } } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public System.Xml.Linq.XAttribute PreviousAttribute { get { return default(System.Xml.Linq.XAttribute); } } public string Value { get { return default(string); } set { } } [System.CLSCompliantAttribute(false)] public static explicit operator bool (System.Xml.Linq.XAttribute attribute) { return default(bool); } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime(System.Xml.Linq.XAttribute attribute) { return default(System.DateTime); } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset(System.Xml.Linq.XAttribute attribute) { return default(System.DateTimeOffset); } [System.CLSCompliantAttribute(false)] public static explicit operator decimal (System.Xml.Linq.XAttribute attribute) { return default(decimal); } [System.CLSCompliantAttribute(false)] public static explicit operator double (System.Xml.Linq.XAttribute attribute) { return default(double); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid(System.Xml.Linq.XAttribute attribute) { return default(System.Guid); } [System.CLSCompliantAttribute(false)] public static explicit operator int (System.Xml.Linq.XAttribute attribute) { return default(int); } [System.CLSCompliantAttribute(false)] public static explicit operator long (System.Xml.Linq.XAttribute attribute) { return default(long); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<bool>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<bool>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.DateTime>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<System.DateTime>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.DateTimeOffset>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<System.DateTimeOffset>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<decimal>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<decimal>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<double>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<double>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.Guid>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<System.Guid>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<int>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<int>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<long>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<long>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<float>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<float>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.TimeSpan>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<System.TimeSpan>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<uint>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<uint>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<ulong>(System.Xml.Linq.XAttribute attribute) { return default(System.Nullable<ulong>); } [System.CLSCompliantAttribute(false)] public static explicit operator float (System.Xml.Linq.XAttribute attribute) { return default(float); } [System.CLSCompliantAttribute(false)] public static explicit operator string (System.Xml.Linq.XAttribute attribute) { return default(string); } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan(System.Xml.Linq.XAttribute attribute) { return default(System.TimeSpan); } [System.CLSCompliantAttribute(false)] public static explicit operator uint (System.Xml.Linq.XAttribute attribute) { return default(uint); } [System.CLSCompliantAttribute(false)] public static explicit operator ulong (System.Xml.Linq.XAttribute attribute) { return default(ulong); } public void Remove() { } public void SetValue(object value) { } public override string ToString() { return default(string); } } public partial class XCData : System.Xml.Linq.XText { public XCData(string value) : base(default(string)) { } public XCData(System.Xml.Linq.XCData other) : base(default(string)) { } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public override void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XComment : System.Xml.Linq.XNode { public XComment(string value) { } public XComment(System.Xml.Linq.XComment other) { } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public string Value { get { return default(string); } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } } public abstract partial class XContainer : System.Xml.Linq.XNode { internal XContainer() { } public System.Xml.Linq.XNode FirstNode { get { return default(System.Xml.Linq.XNode); } } public System.Xml.Linq.XNode LastNode { get { return default(System.Xml.Linq.XNode); } } public void Add(object content) { } public void Add(params object[] content) { } public void AddFirst(object content) { } public void AddFirst(params object[] content) { } public System.Xml.XmlWriter CreateWriter() { return default(System.Xml.XmlWriter); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Xml.Linq.XElement Element(System.Xml.Linq.XName name) { return default(System.Xml.Linq.XElement); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public void RemoveNodes() { } public void ReplaceNodes(object content) { } public void ReplaceNodes(params object[] content) { } } public partial class XDeclaration { public XDeclaration(string version, string encoding, string standalone) { } public XDeclaration(System.Xml.Linq.XDeclaration other) { } public string Encoding { get { return default(string); } set { } } public string Standalone { get { return default(string); } set { } } public string Version { get { return default(string); } set { } } public override string ToString() { return default(string); } } public partial class XDocument : System.Xml.Linq.XContainer { public XDocument() { } public XDocument(params object[] content) { } public XDocument(System.Xml.Linq.XDeclaration declaration, params object[] content) { } public XDocument(System.Xml.Linq.XDocument other) { } public System.Xml.Linq.XDeclaration Declaration { get { return default(System.Xml.Linq.XDeclaration); } set { } } public System.Xml.Linq.XDocumentType DocumentType { get { return default(System.Xml.Linq.XDocumentType); } } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public System.Xml.Linq.XElement Root { get { return default(System.Xml.Linq.XElement); } } public static System.Xml.Linq.XDocument Load(System.IO.Stream stream) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(string uri) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(string uri, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Parse(string text) { return default(System.Xml.Linq.XDocument); } public static System.Xml.Linq.XDocument Parse(string text, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XDocument); } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public override void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XDocumentType : System.Xml.Linq.XNode { public XDocumentType(string name, string publicId, string systemId, string internalSubset) { } public XDocumentType(System.Xml.Linq.XDocumentType other) { } public string InternalSubset { get { return default(string); } set { } } public string Name { get { return default(string); } set { } } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public string PublicId { get { return default(string); } set { } } public string SystemId { get { return default(string); } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XElement : System.Xml.Linq.XContainer, System.Xml.Serialization.IXmlSerializable { public XElement(System.Xml.Linq.XElement other) { } public XElement(System.Xml.Linq.XName name) { } public XElement(System.Xml.Linq.XName name, object content) { } public XElement(System.Xml.Linq.XName name, params object[] content) { } public XElement(System.Xml.Linq.XStreamingElement other) { } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> EmptySequence { get { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } } public System.Xml.Linq.XAttribute FirstAttribute { get { return default(System.Xml.Linq.XAttribute); } } public bool HasAttributes { get { return default(bool); } } public bool HasElements { get { return default(bool); } } public bool IsEmpty { get { return default(bool); } } public System.Xml.Linq.XAttribute LastAttribute { get { return default(System.Xml.Linq.XAttribute); } } public System.Xml.Linq.XName Name { get { return default(System.Xml.Linq.XName); } set { } } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public string Value { get { return default(string); } set { } } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName name) { return default(System.Xml.Linq.XAttribute); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Xml.Linq.XNamespace GetDefaultNamespace() { return default(System.Xml.Linq.XNamespace); } public System.Xml.Linq.XNamespace GetNamespaceOfPrefix(string prefix) { return default(System.Xml.Linq.XNamespace); } public string GetPrefixOfNamespace(System.Xml.Linq.XNamespace ns) { return default(string); } public static System.Xml.Linq.XElement Load(System.IO.Stream stream) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(string uri) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(string uri, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XElement); } [System.CLSCompliantAttribute(false)] public static explicit operator bool (System.Xml.Linq.XElement element) { return default(bool); } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime(System.Xml.Linq.XElement element) { return default(System.DateTime); } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset(System.Xml.Linq.XElement element) { return default(System.DateTimeOffset); } [System.CLSCompliantAttribute(false)] public static explicit operator decimal (System.Xml.Linq.XElement element) { return default(decimal); } [System.CLSCompliantAttribute(false)] public static explicit operator double (System.Xml.Linq.XElement element) { return default(double); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid(System.Xml.Linq.XElement element) { return default(System.Guid); } [System.CLSCompliantAttribute(false)] public static explicit operator int (System.Xml.Linq.XElement element) { return default(int); } [System.CLSCompliantAttribute(false)] public static explicit operator long (System.Xml.Linq.XElement element) { return default(long); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<bool>(System.Xml.Linq.XElement element) { return default(System.Nullable<bool>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.DateTime>(System.Xml.Linq.XElement element) { return default(System.Nullable<System.DateTime>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.DateTimeOffset>(System.Xml.Linq.XElement element) { return default(System.Nullable<System.DateTimeOffset>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<decimal>(System.Xml.Linq.XElement element) { return default(System.Nullable<decimal>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<double>(System.Xml.Linq.XElement element) { return default(System.Nullable<double>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.Guid>(System.Xml.Linq.XElement element) { return default(System.Nullable<System.Guid>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<int>(System.Xml.Linq.XElement element) { return default(System.Nullable<int>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<long>(System.Xml.Linq.XElement element) { return default(System.Nullable<long>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<float>(System.Xml.Linq.XElement element) { return default(System.Nullable<float>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<System.TimeSpan>(System.Xml.Linq.XElement element) { return default(System.Nullable<System.TimeSpan>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<uint>(System.Xml.Linq.XElement element) { return default(System.Nullable<uint>); } [System.CLSCompliantAttribute(false)] public static explicit operator System.Nullable<ulong>(System.Xml.Linq.XElement element) { return default(System.Nullable<ulong>); } [System.CLSCompliantAttribute(false)] public static explicit operator float (System.Xml.Linq.XElement element) { return default(float); } [System.CLSCompliantAttribute(false)] public static explicit operator string (System.Xml.Linq.XElement element) { return default(string); } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan(System.Xml.Linq.XElement element) { return default(System.TimeSpan); } [System.CLSCompliantAttribute(false)] public static explicit operator uint (System.Xml.Linq.XElement element) { return default(uint); } [System.CLSCompliantAttribute(false)] public static explicit operator ulong (System.Xml.Linq.XElement element) { return default(ulong); } public static System.Xml.Linq.XElement Parse(string text) { return default(System.Xml.Linq.XElement); } public static System.Xml.Linq.XElement Parse(string text, System.Xml.Linq.LoadOptions options) { return default(System.Xml.Linq.XElement); } public void RemoveAll() { } public void RemoveAttributes() { } public void ReplaceAll(object content) { } public void ReplaceAll(params object[] content) { } public void ReplaceAttributes(object content) { } public void ReplaceAttributes(params object[] content) { } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public void SetAttributeValue(System.Xml.Linq.XName name, object value) { } public void SetElementValue(System.Xml.Linq.XName name, object value) { } public void SetValue(object value) { } System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { return default(System.Xml.Schema.XmlSchema); } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public override void WriteTo(System.Xml.XmlWriter writer) { } } public sealed partial class XName : System.IEquatable<System.Xml.Linq.XName> { internal XName() { } public string LocalName { get { return default(string); } } public System.Xml.Linq.XNamespace Namespace { get { return default(System.Xml.Linq.XNamespace); } } public string NamespaceName { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public static System.Xml.Linq.XName Get(string expandedName) { return default(System.Xml.Linq.XName); } public static System.Xml.Linq.XName Get(string localName, string namespaceName) { return default(System.Xml.Linq.XName); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { return default(bool); } [System.CLSCompliantAttribute(false)] public static implicit operator System.Xml.Linq.XName(string expandedName) { return default(System.Xml.Linq.XName); } public static bool operator !=(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { return default(bool); } bool System.IEquatable<System.Xml.Linq.XName>.Equals(System.Xml.Linq.XName other) { return default(bool); } public override string ToString() { return default(string); } } public sealed partial class XNamespace { internal XNamespace() { } public string NamespaceName { get { return default(string); } } public static System.Xml.Linq.XNamespace None { get { return default(System.Xml.Linq.XNamespace); } } public static System.Xml.Linq.XNamespace Xml { get { return default(System.Xml.Linq.XNamespace); } } public static System.Xml.Linq.XNamespace Xmlns { get { return default(System.Xml.Linq.XNamespace); } } public override bool Equals(object obj) { return default(bool); } public static System.Xml.Linq.XNamespace Get(string namespaceName) { return default(System.Xml.Linq.XNamespace); } public override int GetHashCode() { return default(int); } public System.Xml.Linq.XName GetName(string localName) { return default(System.Xml.Linq.XName); } public static System.Xml.Linq.XName operator +(System.Xml.Linq.XNamespace ns, string localName) { return default(System.Xml.Linq.XName); } public static bool operator ==(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { return default(bool); } [System.CLSCompliantAttribute(false)] public static implicit operator System.Xml.Linq.XNamespace(string namespaceName) { return default(System.Xml.Linq.XNamespace); } public static bool operator !=(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { return default(bool); } public override string ToString() { return default(string); } } public abstract partial class XNode : System.Xml.Linq.XObject { internal XNode() { } public static System.Xml.Linq.XNodeDocumentOrderComparer DocumentOrderComparer { get { return default(System.Xml.Linq.XNodeDocumentOrderComparer); } } public static System.Xml.Linq.XNodeEqualityComparer EqualityComparer { get { return default(System.Xml.Linq.XNodeEqualityComparer); } } public System.Xml.Linq.XNode NextNode { get { return default(System.Xml.Linq.XNode); } } public System.Xml.Linq.XNode PreviousNode { get { return default(System.Xml.Linq.XNode); } } public void AddAfterSelf(object content) { } public void AddAfterSelf(params object[] content) { } public void AddBeforeSelf(object content) { } public void AddBeforeSelf(params object[] content) { } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public static int CompareDocumentOrder(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { return default(int); } public System.Xml.XmlReader CreateReader() { return default(System.Xml.XmlReader); } public System.Xml.XmlReader CreateReader(System.Xml.Linq.ReaderOptions readerOptions) { return default(System.Xml.XmlReader); } public static bool DeepEquals(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { return default(bool); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf(System.Xml.Linq.XName name) { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>); } public bool IsAfter(System.Xml.Linq.XNode node) { return default(bool); } public bool IsBefore(System.Xml.Linq.XNode node) { return default(bool); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesAfterSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesBeforeSelf() { return default(System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>); } public static System.Xml.Linq.XNode ReadFrom(System.Xml.XmlReader reader) { return default(System.Xml.Linq.XNode); } public void Remove() { } public void ReplaceWith(object content) { } public void ReplaceWith(params object[] content) { } public override string ToString() { return default(string); } public string ToString(System.Xml.Linq.SaveOptions options) { return default(string); } public abstract void WriteTo(System.Xml.XmlWriter writer); } public sealed partial class XNodeDocumentOrderComparer : System.Collections.Generic.IComparer<System.Xml.Linq.XNode>, System.Collections.IComparer { public XNodeDocumentOrderComparer() { } public int Compare(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { return default(int); } int System.Collections.IComparer.Compare(object x, object y) { return default(int); } } public sealed partial class XNodeEqualityComparer : System.Collections.Generic.IEqualityComparer<System.Xml.Linq.XNode>, System.Collections.IEqualityComparer { public XNodeEqualityComparer() { } public bool Equals(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { return default(bool); } public int GetHashCode(System.Xml.Linq.XNode obj) { return default(int); } bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); } int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); } } public abstract partial class XObject : System.Xml.IXmlLineInfo { internal XObject() { } public string BaseUri { get { return default(string); } } public System.Xml.Linq.XDocument Document { get { return default(System.Xml.Linq.XDocument); } } public abstract System.Xml.XmlNodeType NodeType { get; } public System.Xml.Linq.XElement Parent { get { return default(System.Xml.Linq.XElement); } } int System.Xml.IXmlLineInfo.LineNumber { get { return default(int); } } int System.Xml.IXmlLineInfo.LinePosition { get { return default(int); } } public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changed { add { } remove { } } public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changing { add { } remove { } } public void AddAnnotation(object annotation) { } public object Annotation(System.Type type) { return default(object); } public T Annotation<T>() where T : class { return default(T); } public System.Collections.Generic.IEnumerable<object> Annotations(System.Type type) { return default(System.Collections.Generic.IEnumerable<object>); } public System.Collections.Generic.IEnumerable<T> Annotations<T>() where T : class { return default(System.Collections.Generic.IEnumerable<T>); } public void RemoveAnnotations(System.Type type) { } public void RemoveAnnotations<T>() where T : class { } bool System.Xml.IXmlLineInfo.HasLineInfo() { return default(bool); } } public enum XObjectChange { Add = 0, Name = 2, Remove = 1, Value = 3, } public partial class XObjectChangeEventArgs : System.EventArgs { public static readonly System.Xml.Linq.XObjectChangeEventArgs Add; public static readonly System.Xml.Linq.XObjectChangeEventArgs Name; public static readonly System.Xml.Linq.XObjectChangeEventArgs Remove; public static readonly System.Xml.Linq.XObjectChangeEventArgs Value; public XObjectChangeEventArgs(System.Xml.Linq.XObjectChange objectChange) { } public System.Xml.Linq.XObjectChange ObjectChange { get { return default(System.Xml.Linq.XObjectChange); } } } public partial class XProcessingInstruction : System.Xml.Linq.XNode { public XProcessingInstruction(string target, string data) { } public XProcessingInstruction(System.Xml.Linq.XProcessingInstruction other) { } public string Data { get { return default(string); } set { } } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public string Target { get { return default(string); } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XStreamingElement { public XStreamingElement(System.Xml.Linq.XName name) { } public XStreamingElement(System.Xml.Linq.XName name, object content) { } public XStreamingElement(System.Xml.Linq.XName name, params object[] content) { } public System.Xml.Linq.XName Name { get { return default(System.Xml.Linq.XName); } set { } } public void Add(object content) { } public void Add(params object[] content) { } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public override string ToString() { return default(string); } public string ToString(System.Xml.Linq.SaveOptions options) { return default(string); } public void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XText : System.Xml.Linq.XNode { public XText(string value) { } public XText(System.Xml.Linq.XText other) { } public override System.Xml.XmlNodeType NodeType { get { return default(System.Xml.XmlNodeType); } } public string Value { get { return default(string); } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } } }
// Modified off Nate Kohari's xunit.should: // http://github.com/enkari/xunit.should using System; using System.Collections; using System.Collections.Generic; //Move to the Xunit namespace to save us from the extra namespace import. namespace Xunit { public static class ShouldExtensions { public static void ShouldContain(this string self, string str) { Assert.Contains(str, self); } public static void ShouldContain(this string self, string str, StringComparison comparison) { Assert.Contains(str, self, comparison); } public static void ShouldContain<T>(this IEnumerable<T> series, T item) { Assert.Contains(item, series); } public static void ShouldContain<T>(this IEnumerable<T> series, T item, IEqualityComparer<T> comparer) { Assert.Contains(item, series, comparer); } public static void ShouldNotContain(this string self, string str) { Assert.DoesNotContain(str, self); } public static void ShouldNotContain(this string self, string str, StringComparison comparison) { Assert.DoesNotContain(str, self, comparison); } public static void ShouldNotContain<T>(this IEnumerable<T> series, T item) { Assert.DoesNotContain(item, series); } public static void ShouldNotContain<T>(this IEnumerable<T> series, T item, IEqualityComparer<T> comparer) { Assert.DoesNotContain(item, series, comparer); } public static void ShouldBeEmpty(this IEnumerable series) { Assert.Empty(series); } public static void ShouldNotBeEmpty(this IEnumerable series) { Assert.NotEmpty(series); } public static void ShouldBe<T>(this T self, T other) { Assert.Equal(other, self); } public static void ShouldBe<T>(this T self, T other, IEqualityComparer<T> comparer) { Assert.Equal(other, self, comparer); } public static void ShouldNotBe<T>(this T self, T other) { Assert.NotEqual(other, self); } public static void ShouldNotBe<T>(this T self, T other, IEqualityComparer<T> comparer) { Assert.NotEqual(other, self, comparer); } public static void ShouldBeNull(this object self) { Assert.Null(self); } public static void ShouldNotBeNull(this object self) { Assert.NotNull(self); } public static void ShouldBeSameAs(this object self, object other) { Assert.Same(other, self); } public static void ShouldNotBeSameAs(this object self, object other) { Assert.NotSame(other, self); } public static void ShouldBeTrue(this bool self) { Assert.True(self); } public static void ShouldBeTrue(this bool self, string message) { Assert.True(self, message); } public static void ShouldBeFalse(this bool self) { Assert.False(self); } public static void ShouldBeFalse(this bool self, string message) { Assert.False(self, message); } public static void ShouldBeInRange<T>(this T self, T low, T high) where T : IComparable { Assert.InRange(self, low, high); } public static void ShouldNotBeInRange<T>(this T self, T low, T high) where T : IComparable { Assert.NotInRange(self, low, high); } public static void ShouldBeGreaterThan<T>(this T self, T other) where T : IComparable<T> { Assert.True(self.CompareTo(other) > 0); } public static void ShouldBeGreaterThan<T>(this T self, T other, IComparer<T> comparer) { Assert.True(comparer.Compare(self, other) > 0); } public static void ShouldBeGreaterThanOrEqualTo<T>(this T self, T other) where T : IComparable<T> { Assert.True(self.CompareTo(other) >= 0); } public static void ShouldBeGreaterThanOrEqualTo<T>(this T self, T other, IComparer<T> comparer) { Assert.True(comparer.Compare(self, other) >= 0); } public static void ShouldBeLessThan<T>(this T self, T other) where T : IComparable<T> { Assert.True(self.CompareTo(other) < 0); } public static void ShouldBeLessThan<T>(this T self, T other, IComparer<T> comparer) { Assert.True(comparer.Compare(self, other) < 0); } public static void ShouldBeLessThanOrEqualTo<T>(this T self, T other) where T : IComparable<T> { Assert.True(self.CompareTo(other) <= 0); } public static void ShouldBeLessThanOrEqualTo<T>(this T self, T other, IComparer<T> comparer) { Assert.True(comparer.Compare(self, other) <= 0); } public static void ShouldBeInstanceOf<T>(this object self) { Assert.IsType<T>(self); } public static void ShouldBeInstanceOf(this object self, Type type) { Assert.IsType(type, self); } public static void ShouldNotBeInstanceOf<T>(this object self) { Assert.IsNotType<T>(self); } public static void ShouldNotBeInstanceOf(this object self, Type type) { Assert.IsNotType(type, self); } public static void ShouldBeThrownBy<T>(this T self, Assert.ThrowsDelegate method) where T : Exception { Assert.Throws<T>(method); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Linq; using QuantConnect.Data; using QuantConnect.Util; using System.Diagnostics; using QuantConnect.Logging; using System.Threading.Tasks; using System.Collections.Generic; using QuantConnect.ToolBox.CoinApi; namespace QuantConnect.ToolBox.CoinApiDataConverter { /// <summary> /// Console application for converting CoinApi raw data into Lean data format for high resolutions (tick, second and minute) /// </summary> public class CoinApiDataConverter { /// <summary> /// List of supported exchanges /// </summary> private static readonly HashSet<string> SupportedMarkets = new[] { Market.GDAX, Market.Bitfinex, Market.Binance, Market.FTX, Market.FTXUS, Market.Kraken, Market.BinanceUS }.ToHashSet(); private readonly DirectoryInfo _rawDataFolder; private readonly DirectoryInfo _destinationFolder; private readonly DateTime _processingDate; private readonly string _market; /// <summary> /// CoinAPI data converter. /// </summary> /// <param name="date">the processing date.</param> /// <param name="rawDataFolder">path to the raw data folder.</param> /// <param name="destinationFolder">destination of the newly generated files.</param> /// <param name="market">The market to process (optional). Defaults to processing all markets in parallel.</param> public CoinApiDataConverter(DateTime date, string rawDataFolder, string destinationFolder, string market = null) { _market = string.IsNullOrWhiteSpace(market) ? null : market.ToLowerInvariant(); _processingDate = date; _rawDataFolder = new DirectoryInfo(Path.Combine(rawDataFolder, SecurityType.Crypto.ToLower(), "coinapi")); if (!_rawDataFolder.Exists) { throw new ArgumentException($"CoinApiDataConverter(): Source folder not found: {_rawDataFolder.FullName}"); } _destinationFolder = new DirectoryInfo(destinationFolder); _destinationFolder.Create(); } /// <summary> /// Runs this instance. /// </summary> /// <returns></returns> public bool Run() { var stopwatch = Stopwatch.StartNew(); var symbolMapper = new CoinApiSymbolMapper(); var success = true; // There were cases of files with with an extra suffix, following pattern: // <TickType>-<ID>-<Exchange>_SPOT_<BaseCurrency>_<QuoteCurrency>_<ExtraSuffix>.csv.gz // Those cases should be ignored for SPOT prices. var tradesFolder = new DirectoryInfo( Path.Combine( _rawDataFolder.FullName, "trades", _processingDate.ToStringInvariant(DateFormat.EightCharacter))); var quotesFolder = new DirectoryInfo( Path.Combine( _rawDataFolder.FullName, "quotes", _processingDate.ToStringInvariant(DateFormat.EightCharacter))); var rawMarket = _market != null && CoinApiSymbolMapper.MapMarketsToExchangeIds.TryGetValue(_market, out var rawMarketValue) ? rawMarketValue : null; // Distinct by tick type and first two parts of the raw file name, separated by '-'. // This prevents us from double processing the same ticker twice, in case we're given // two raw data files for the same symbol. Related: https://github.com/QuantConnect/Lean/pull/3262 var apiDataReader = new CoinApiDataReader(symbolMapper); var filesToProcessCandidates = tradesFolder.EnumerateFiles("*.gz") .Concat(quotesFolder.EnumerateFiles("*.gz")) .Where(f => f.Name.Contains("SPOT") && (rawMarket == null || f.Name.Contains(rawMarket))) .Where(f => f.Name.Split('_').Length == 4) .ToList(); var filesToProcessKeys = new HashSet<string>(); var filesToProcess = new List<FileInfo>(); foreach (var candidate in filesToProcessCandidates) { try { var entryData = apiDataReader.GetCoinApiEntryData(candidate, _processingDate); CurrencyPairUtil.DecomposeCurrencyPair(entryData.Symbol, out var baseCurrency, out var quoteCurrency); if (!candidate.FullName.Contains(baseCurrency) && !candidate.FullName.Contains(quoteCurrency)) { throw new Exception($"Skipping {candidate.FullName} we have the wrong symbol {entryData.Symbol}!"); } var key = candidate.Directory.Parent.Name + entryData.Symbol.ID; if (filesToProcessKeys.Add(key)) { // Separate list from HashSet to preserve ordering of viable candidates filesToProcess.Add(candidate); } } catch (Exception err) { // Most likely the exchange isn't supported. Log exception message to avoid excessive stack trace spamming in console output Log.Error(err.Message); } } Parallel.ForEach(filesToProcess, (file, loopState) => { Log.Trace($"CoinApiDataConverter(): Starting data conversion from source file: {file.Name}..."); try { ProcessEntry(apiDataReader, file); } catch (Exception e) { Log.Error(e, $"CoinApiDataConverter(): Error processing entry: {file.Name}"); success = false; loopState.Break(); } } ); Log.Trace($"CoinApiDataConverter(): Finished in {stopwatch.Elapsed}"); return success; } /// <summary> /// Processes the entry. /// </summary> /// <param name="coinapiDataReader">The coinapi data reader.</param> /// <param name="file">The file.</param> private void ProcessEntry(CoinApiDataReader coinapiDataReader, FileInfo file) { var entryData = coinapiDataReader.GetCoinApiEntryData(file, _processingDate); if (!SupportedMarkets.Contains(entryData.Symbol.ID.Market)) { // only convert data for supported exchanges return; } var tickData = coinapiDataReader.ProcessCoinApiEntry(entryData, file); // in some cases the first data points from '_processingDate' get's included in the previous date file // so we will ready previous date data and drop most of it just to save these midnight ticks var yesterdayDate = _processingDate.AddDays(-1); var yesterdaysFile = new FileInfo(file.FullName.Replace( _processingDate.ToStringInvariant(DateFormat.EightCharacter), yesterdayDate.ToStringInvariant(DateFormat.EightCharacter))); if (yesterdaysFile.Exists) { var yesterdaysEntryData = coinapiDataReader.GetCoinApiEntryData(yesterdaysFile, yesterdayDate); tickData = tickData.Concat(coinapiDataReader.ProcessCoinApiEntry(yesterdaysEntryData, yesterdaysFile)); } else { Log.Error($"CoinApiDataConverter(): yesterdays data file not found '{yesterdaysFile.FullName}'"); } // materialize the enumerable into a list, since we need to enumerate over it twice var ticks = tickData.Where(tick => tick.Time.Date == _processingDate) .OrderBy(t => t.Time) .ToList(); var writer = new LeanDataWriter(Resolution.Tick, entryData.Symbol, _destinationFolder.FullName, entryData.TickType); writer.Write(ticks); Log.Trace($"CoinApiDataConverter(): Starting consolidation for {entryData.Symbol.Value} {entryData.TickType}"); var consolidators = new List<TickAggregator>(); if (entryData.TickType == TickType.Trade) { consolidators.AddRange(new[] { new TradeTickAggregator(Resolution.Second), new TradeTickAggregator(Resolution.Minute) }); } else { consolidators.AddRange(new[] { new QuoteTickAggregator(Resolution.Second), new QuoteTickAggregator(Resolution.Minute) }); } foreach (var tick in ticks) { if (tick.Suspicious) { // When CoinAPI loses connectivity to the exchange, they indicate // it in the data by providing a value of `-1` for bid/ask price. // We will keep it in tick data, but will remove it from consolidated data. continue; } foreach (var consolidator in consolidators) { consolidator.Update(tick); } } foreach (var consolidator in consolidators) { writer = new LeanDataWriter(consolidator.Resolution, entryData.Symbol, _destinationFolder.FullName, entryData.TickType); writer.Write(consolidator.Flush()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; using System.Transactions; using Microsoft.SqlServer.Server; using System.Reflection; using System.IO; using System.Globalization; namespace System.Data.SqlClient { public sealed partial class SqlConnection : DbConnection, ICloneable { private bool _AsyncCommandInProgress; // SQLStatistics support internal SqlStatistics _statistics; private bool _collectstats; private bool _fireInfoMessageEventOnUserErrors; // False by default // root task associated with current async invocation private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion; private string _connectionString; private int _connectRetryCount; // connection resiliency private object _reconnectLock = new object(); internal Task _currentReconnectionTask; private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections private Guid _originalConnectionId = Guid.Empty; private CancellationTokenSource _reconnectionCancellationSource; internal SessionData _recoverySessionData; internal bool _suppressStateChangeForReconnection; private int _reconnectCount; // diagnostics listener private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName); // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened // using SqlConnection.Open() method. internal bool _applyTransientFaultHandling = false; public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available CacheConnectionStringProperties(); } private SqlConnection(SqlConnection connection) { GC.SuppressFinalize(this); CopyFrom(connection); _connectionString = connection._connectionString; CacheConnectionStringProperties(); } // This method will be called once connection string is set or changed. private void CacheConnectionStringProperties() { SqlConnectionString connString = ConnectionOptions as SqlConnectionString; if (connString != null) { _connectRetryCount = connString.ConnectRetryCount; } } // // PUBLIC PROPERTIES // // used to start/stop collection of statistics data and do verify the current state // // devnote: start/stop should not performed using a property since it requires execution of code // // start statistics // set the internal flag (_statisticsEnabled) to true. // Create a new SqlStatistics object if not already there. // connect the parser to the object. // if there is no parser at this time we need to connect it after creation. // public bool StatisticsEnabled { get { return (_collectstats); } set { { if (value) { // start if (ConnectionState.Open == State) { if (null == _statistics) { _statistics = new SqlStatistics(); ADP.TimerCurrent(out _statistics._openTimestamp); } // set statistics on the parser // update timestamp; Debug.Assert(Parser != null, "Where's the parser?"); Parser.Statistics = _statistics; } } else { // stop if (null != _statistics) { if (ConnectionState.Open == State) { // remove statistics from parser // update timestamp; TdsParser parser = Parser; Debug.Assert(parser != null, "Where's the parser?"); parser.Statistics = null; ADP.TimerCurrent(out _statistics._closeTimestamp); } } } _collectstats = value; } } } internal bool AsyncCommandInProgress { get => _AsyncCommandInProgress; set => _AsyncCommandInProgress = value; } internal SqlConnectionString.TransactionBindingEnum TransactionBinding { get => ((SqlConnectionString)ConnectionOptions).TransactionBinding; } internal SqlConnectionString.TypeSystem TypeSystem { get => ((SqlConnectionString)ConnectionOptions).TypeSystemVersion; } internal Version TypeSystemAssemblyVersion { get => ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion; } internal int ConnectRetryInterval { get => ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval; } public override string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(new SqlConnectionPoolKey(value)); _connectionString = value; // Change _connectionString value only after value is validated CacheConnectionStringProperties(); } } public override int ConnectionTimeout { get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); } } public override string Database { // if the connection is open, we need to ask the inner connection what it's // current catalog is because it may have gotten changed, otherwise we can // just return what the connection string had. get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); } return result; } } public override string DataSource { get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); } return result; } } public int PacketSize { // if the connection is open, we need to ask the inner connection what it's // current packet size is because it may have gotten changed, otherwise we // can just return what the connection string had. get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; if (null != innerConnection) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); } return result; } } public Guid ClientConnectionId { get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null != innerConnection) { return innerConnection.ClientConnectionId; } else { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return _originalConnectionId; } return Guid.Empty; } } } public override string ServerVersion { get => GetOpenTdsConnection().ServerVersion; } public override ConnectionState State { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return ConnectionState.Open; } return InnerConnection.State; } } internal SqlStatistics Statistics { get => _statistics; } public string WorkstationId { get { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; string result = ((null != constr) ? constr.WorkstationId : string.Empty); return result; } } protected override DbProviderFactory DbProviderFactory { get => SqlClientFactory.Instance; } // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication // // PUBLIC EVENTS // public event SqlInfoMessageEventHandler InfoMessage; public bool FireInfoMessageEventOnUserErrors { get => _fireInfoMessageEventOnUserErrors; set => _fireInfoMessageEventOnUserErrors = value; } // Approx. number of times that the internal connection has been reconnected internal int ReconnectCount { get => _reconnectCount; } internal bool ForceNewConnection { get; set; } protected override void OnStateChange(StateChangeEventArgs stateChange) { if (!_suppressStateChangeForReconnection) { base.OnStateChange(stateChange); } } // // PUBLIC METHODS // new public SqlTransaction BeginTransaction() { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(IsolationLevel.Unspecified, null); } new public SqlTransaction BeginTransaction(IsolationLevel iso) { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(iso, null); } public SqlTransaction BeginTransaction(string transactionName) { // Use transaction names only on the outermost pair of nested // BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names // are ignored for nested BEGIN's. The only way to rollback a nested // transaction is to have a save point from a SAVE TRANSACTION call. return BeginTransaction(IsolationLevel.Unspecified, transactionName); } [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) { WaitForPendingReconnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlTransaction transaction; bool isFirstAttempt = true; do { transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt"); isFirstAttempt = false; } while (transaction.InternalTransaction.ConnectionHasBeenRestored); // The GetOpenConnection line above doesn't keep a ref on the outer connection (this), // and it could be collected before the inner connection can hook it to the transaction, resulting in // a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen. GC.KeepAlive(this); return transaction; } finally { SqlStatistics.StopTimer(statistics); } } public override void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); try { statistics = SqlStatistics.StartTimer(Statistics); InnerConnection.ChangeDatabase(database); } finally { SqlStatistics.StopTimer(statistics); } } public static void ClearAllPools() { SqlConnectionFactory.SingletonInstance.ClearAllPools(); } public static void ClearPool(SqlConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; if (null != connectionOptions) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } } private void CloseInnerConnection() { // CloseConnection() now handles the lock // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is // outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock. InnerConnection.CloseConnection(this, ConnectionFactory); } public override void Close() { ConnectionState previousState = State; Guid operationId = default(Guid); Guid clientConnectionId = default(Guid); // during the call to Dispose() there is a redundant call to // Close(). because of this, the second time Close() is invoked the // connection is already in a closed state. this doesn't seem to be a // problem except for logging, as we'll get duplicate Before/After/Error // log entries if (previousState != ConnectionState.Closed) { operationId = s_diagnosticListener.WriteConnectionCloseBefore(this); // we want to cache the ClientConnectionId for After/Error logging, as when the connection // is closed then we will lose this identifier // // note: caching this is only for diagnostics logging purposes clientConnectionId = ClientConnectionId; } SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { CancellationTokenSource cts = _reconnectionCancellationSource; if (cts != null) { cts.Cancel(); } AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection if (State != ConnectionState.Open) {// if we cancelled before the connection was opened OnStateChange(DbConnectionInternal.StateChangeClosed); } } CancelOpenAndWait(); CloseInnerConnection(); GC.SuppressFinalize(this); if (null != Statistics) { ADP.TimerCurrent(out _statistics._closeTimestamp); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); // we only want to log this if the previous state of the // connection is open, as that's the valid use-case if (previousState != ConnectionState.Closed) { if (e != null) { s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e); } else { s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this); } } } } new public SqlCommand CreateCommand() { return new SqlCommand(null, this); } private void DisposeMe(bool disposing) { if (!disposing) { // For non-pooled connections we need to make sure that if the SqlConnection was not closed, // then we release the GCHandle on the stateObject to allow it to be GCed // For pooled connections, we will rely on the pool reclaiming the connection var innerConnection = (InnerConnection as SqlInternalConnectionTds); if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) { var parser = innerConnection.Parser; if ((parser != null) && (parser._physicalStateObj != null)) { parser._physicalStateObj.DecrementPendingCallbacks(release: false); } } } } public override void Open() { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); if (!TryOpen(null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } } } internal void RegisterWaitingForReconnect(Task waitingTask) { if (((SqlConnectionString)ConnectionOptions).MARS) { return; } Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null); if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register throw SQL.MARSUnspportedOnConnection(); } } private async Task ReconnectAsync(int timeout) { try { long commandTimeoutExpiration = 0; if (timeout > 0) { commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout); } CancellationTokenSource cts = new CancellationTokenSource(); _reconnectionCancellationSource = cts; CancellationToken ctoken = cts.Token; int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string for (int attempt = 0; attempt < retryCount; attempt++) { if (ctoken.IsCancellationRequested) { return; } try { try { ForceNewConnection = true; await OpenAsync(ctoken).ConfigureAwait(false); // On success, increment the reconnect count - we don't really care if it rolls over since it is approx. _reconnectCount = unchecked(_reconnectCount + 1); #if DEBUG Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !"); #endif } finally { ForceNewConnection = false; } return; } catch (SqlException e) { if (attempt == retryCount - 1) { throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) { throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId); } } await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false); } } finally { _recoverySessionData = null; _suppressStateChangeForReconnection = false; } Debug.Assert(false, "Should not reach this point"); } internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { Task runningReconnect = _currentReconnectionTask; // This loop in the end will return not completed reconnect task or null while (runningReconnect != null && runningReconnect.IsCompleted) { // clean current reconnect task (if it is the same one we checked Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect); // make sure nobody started new task (if which case we did not clean it) runningReconnect = _currentReconnectionTask; } if (runningReconnect == null) { if (_connectRetryCount > 0) { SqlInternalConnectionTds tdsConn = GetOpenTdsConnection(); if (tdsConn._sessionRecoveryAcknowledged) { TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj; if (!stateObj.ValidateSNIConnection()) { if (tdsConn.Parser._sessionPool != null) { if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0) { // >1 MARS session if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null); } } SessionData cData = tdsConn.CurrentSessionData; cData.AssertUnrecoverableStateCountIsCorrect(); if (cData._unrecoverableStatesCount == 0) { bool callDisconnect = false; lock (_reconnectLock) { tdsConn.CheckEnlistedTransactionBinding(); runningReconnect = _currentReconnectionTask; // double check after obtaining the lock if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; _recoverySessionData = cData; if (beforeDisconnect != null) { beforeDisconnect(); } try { _suppressStateChangeForReconnection = true; tdsConn.DoomThisConnection(); } catch (SqlException) { } runningReconnect = Task.Run(() => ReconnectAsync(timeout)); // if current reconnect is not null, somebody already started reconnection task - some kind of race condition Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected"); _currentReconnectionTask = runningReconnect; } } else { callDisconnect = true; } } if (callDisconnect && beforeDisconnect != null) { beforeDisconnect(); } } else { if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null); } } // ValidateSNIConnection } // sessionRecoverySupported } // connectRetryCount>0 } else { // runningReconnect = null if (beforeDisconnect != null) { beforeDisconnect(); } } return runningReconnect; } // this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request partial void RepairInnerConnection() { WaitForPendingReconnection(); if (_connectRetryCount == 0) { return; } SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds; if (tdsConn != null) { tdsConn.ValidateConnectionForExecute(null); tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this); } } private void WaitForPendingReconnection() { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); } } private void CancelOpenAndWait() { // copy from member to avoid changes by background thread var completion = _currentCompletion; if (completion != null) { completion.Item1.TrySetCanceled(); ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne(); } Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source"); } public override Task OpenAsync(CancellationToken cancellationToken) { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); System.Transactions.Transaction transaction = ADP.GetCurrentTransaction(); TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction); TaskCompletionSource<object> result = new TaskCompletionSource<object>(); if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection)) { result.Task.ContinueWith((t) => { if (t.Exception != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } }, TaskScheduler.Default); } if (cancellationToken.IsCancellationRequested) { result.SetCanceled(); return result.Task; } bool completed; try { completed = TryOpen(completion); } catch (Exception e) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); result.SetException(e); return result.Task; } if (completed) { result.SetResult(null); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion); } OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration); _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task); completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default); return result.Task; } return result.Task; } catch (Exception ex) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex); throw; } finally { SqlStatistics.StopTimer(statistics); } } public override DataTable GetSchema() { return GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null); } public override DataTable GetSchema(string collectionName) { return GetSchema(collectionName, null); } public override DataTable GetSchema(string collectionName, string[] restrictionValues) { return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues); } private class OpenAsyncRetry { private SqlConnection _parent; private TaskCompletionSource<DbConnectionInternal> _retry; private TaskCompletionSource<object> _result; private CancellationTokenRegistration _registration; public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration) { _parent = parent; _retry = retry; _result = result; _registration = registration; } internal void Retry(Task<DbConnectionInternal> retryTask) { _registration.Dispose(); try { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(_parent.Statistics); if (retryTask.IsFaulted) { Exception e = retryTask.Exception.InnerException; _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(retryTask.Exception.InnerException); } else if (retryTask.IsCanceled) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetCanceled(); } else { bool result; // protect continuation from races with close and cancel lock (_parent.InnerConnection) { result = _parent.TryOpen(_retry); } if (result) { _parent._currentCompletion = null; _result.SetResult(null); } else { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending))); } } } finally { SqlStatistics.StopTimer(statistics); } } catch (Exception e) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(e); } } } private void PrepareStatisticsForNewConnection() { if (StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection)) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } } private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry) { SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions; _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0); if (ForceNewConnection) { if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } else { if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } // does not require GC.KeepAlive(this) because of OnStateChange var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection; Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?"); if (!tdsInnerConnection.ConnectionOptions.Pooling) { // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles GC.ReRegisterForFinalize(this); } // The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value. SqlStatistics statistics = _statistics; if (StatisticsEnabled || (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null)) { ADP.TimerCurrent(out _statistics._openTimestamp); tdsInnerConnection.Parser.Statistics = _statistics; } else { tdsInnerConnection.Parser.Statistics = null; _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence } return true; } // // INTERNAL PROPERTIES // internal bool HasLocalTransaction { get { return GetOpenTdsConnection().HasLocalTransaction; } } internal bool HasLocalTransactionFromAPI { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return false; //we will not go into reconnection if we are inside the transaction } return GetOpenTdsConnection().HasLocalTransactionFromAPI; } } internal bool IsKatmaiOrNewer { get { if (_currentReconnectionTask != null) { // holds true even if task is completed return true; // if CR is enabled, connection, if established, will be Katmai+ } return GetOpenTdsConnection().IsKatmaiOrNewer; } } internal TdsParser Parser { get { SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection(); return tdsConnection.Parser; } } // // INTERNAL METHODS // internal void ValidateConnectionForExecute(string method, SqlCommand command) { Task asyncWaitingForReconnection = _asyncWaitingForReconnection; if (asyncWaitingForReconnection != null) { if (!asyncWaitingForReconnection.IsCompleted) { throw SQL.MARSUnspportedOnConnection(); } else { Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection); } } if (_currentReconnectionTask != null) { Task currentReconnectionTask = _currentReconnectionTask; if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) { return; // execution will wait for this task later } } SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method); innerConnection.ValidateConnectionForExecute(command); } // Surround name in brackets and then escape any end bracket to protect against SQL Injection. // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well // as native OleDb and Odbc. internal static string FixupDatabaseTransactionName(string name) { if (!string.IsNullOrEmpty(name)) { return SqlServerEscapeHelper.EscapeIdentifier(name); } else { return name; } } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) { Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!"); if (breakConnection && (ConnectionState.Open == State)) { if (wrapCloseInAction != null) { int capturedCloseCount = _closeCount; Action closeAction = () => { if (capturedCloseCount == _closeCount) { Close(); } }; wrapCloseInAction(closeAction); } else { Close(); } } if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error, // below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } else { // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler this.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } } // // PRIVATE METHODS // internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.ClosedConnectionError(); } return innerConnection; } internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.OpenConnectionRequired(method, InnerConnection.State); } return innerConnection; } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) { bool notified; OnInfoMessage(imevent, out notified); } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { notified = true; try { handler(this, imevent); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } else { notified = false; } } // // SQL DEBUGGING SUPPORT // // this only happens once per connection // SxS: using named file mapping APIs internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag) { // Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect outerTask = outerTask.ContinueWith(task => { RemoveWeakReference(value); return task; }, TaskScheduler.Default).Unwrap(); } public void ResetStatistics() { if (null != Statistics) { Statistics.Reset(); if (ConnectionState.Open == State) { // update timestamp; ADP.TimerCurrent(out _statistics._openTimestamp); } } } public IDictionary RetrieveStatistics() { if (null != Statistics) { UpdateStatistics(); return Statistics.GetDictionary(); } else { return new SqlStatistics().GetDictionary(); } } private void UpdateStatistics() { if (ConnectionState.Open == State) { // update timestamp ADP.TimerCurrent(out _statistics._closeTimestamp); } // delegate the rest of the work to the SqlStatistics class Statistics.UpdateStatistics(); } object ICloneable.Clone() => new SqlConnection(this); private void CopyFrom(SqlConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); _userConnectionOptions = connection.UserConnectionOptions; _poolGroup = connection.PoolGroup; if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection) { _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } else { _innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance; } } // UDT SUPPORT private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !"); if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) { asmRef.Version = TypeSystemAssemblyVersion; } try { return Assembly.Load(asmRef); } catch (Exception e) { if (throwOnError || !ADP.IsCatchableExceptionType(e)) { throw; } else { return null; }; } } internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow) { if (metaData.udtType == null) { // If null, we have not obtained extended info. Debug.Assert(!string.IsNullOrEmpty(metaData.udtAssemblyQualifiedName), "Unexpected state on GetUDTInfo"); // Parameter throwOnError determines whether exception from Assembly.Load is thrown. metaData.udtType = Type.GetType(typeName: metaData.udtAssemblyQualifiedName, assemblyResolver: asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver: null, throwOnError: fThrow); if (fThrow && metaData.udtType == null) { throw SQL.UDTUnexpectedResult(metaData.udtAssemblyQualifiedName); } } } internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull) { if (returnDBNull && ADP.IsNull(value)) { return DBNull.Value; } object o = null; // Since the serializer doesn't handle nulls... if (ADP.IsNull(value)) { Type t = metaData.udtType; Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!"); o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, new object[] { }, CultureInfo.InvariantCulture); Debug.Assert(o != null); return o; } else { MemoryStream stm = new MemoryStream((byte[])value); o = SerializationHelperSql9.Deserialize(stm, metaData.udtType); Debug.Assert(o != null, "object could NOT be created"); return o; } } internal byte[] GetBytes(object o) { Format format = Format.Native; return GetBytes(o, out format, out int maxSize); } internal byte[] GetBytes(object o, out Format format, out int maxSize) { SqlUdtInfo attr = GetInfoFromType(o.GetType()); maxSize = attr.MaxByteSize; format = attr.SerializationFormat; if (maxSize < -1 || maxSize >= ushort.MaxValue) { throw new InvalidOperationException(o.GetType() + ": invalid Size"); } byte[] retval; using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize)) { SerializationHelperSql9.Serialize(stm, o); retval = stm.ToArray(); } return retval; } private SqlUdtInfo GetInfoFromType(Type t) { Debug.Assert(t != null, "Type object cant be NULL"); Type orig = t; do { SqlUdtInfo attr = SqlUdtInfo.TryGetFromType(t); if (attr != null) { return attr; } else { t = t.BaseType; } } while (t != null); throw SQL.UDTInvalidSqlType(orig.AssemblyQualifiedName); } } }
// 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 Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { internal static class Certificates { public static readonly CertLoader RSAKeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer1Cer, RawData.s_RSAKeyTransfer1Pfx, "1111"); public static readonly CertLoader RSAKeyTransfer2 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer2Cer, RawData.s_RSAKeyTransfer2Pfx, "1111"); public static readonly CertLoader RSAKeyTransfer3 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer3Cer, RawData.s_RSAKeyTransfer3Pfx, "1111"); public static readonly CertLoader RSAKeyTransfer_ExplicitSki = new CertLoaderFromRawData(RawData.s_RSAKeyTransferCer_ExplicitSki, RawData.s_RSAKeyTransferPfx_ExplicitSki, "1111"); public static readonly CertLoader RSAKeyTransferCapi1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransferCapi1Cer, RawData.s_RSAKeyTransferCapi1Pfx, "1111"); public static readonly CertLoader RSASha256KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha256KeyTransfer1Cer, RawData.s_RSASha256KeyTransfer1Pfx, "1111"); public static readonly CertLoader RSASha384KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha384KeyTransfer1Cer, RawData.s_RSASha384KeyTransfer1Pfx, "1111"); public static readonly CertLoader RSASha512KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha512KeyTransfer1Cer, RawData.s_RSASha512KeyTransfer1Pfx, "1111"); public static readonly CertLoader DHKeyAgree1 = new CertLoaderFromRawData(RawData.s_DHKeyAgree1Cer); public static readonly CertLoader RSA2048SignatureOnly = new CertLoaderFromRawData(RawData.s_Rsa2048SignatureOnlyCer, RawData.s_Rsa2048SignatureOnlyPfx, "12345"); public static readonly CertLoader Dsa1024 = new CertLoaderFromRawData(RawData.s_dsa1024Cert, RawData.s_dsa1024Pfx, "1234"); public static readonly CertLoader ECDsaP256Win = new CertLoaderFromRawData(RawData.ECDsaP256_DigitalSignature_Cert, RawData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test"); public static readonly CertLoader ECDsaP521Win = new CertLoaderFromRawData(RawData.ECDsaP521_DigitalSignature_Cert, RawData.ECDsaP521_DigitalSignature_Pfx_Windows, "Test"); public static readonly CertLoader ValidLookingTsaCert = new CertLoaderFromRawData(RawData.ValidLookingTsaCert_Cer, RawData.ValidLookingTsaCert_Pfx, "export"); public static readonly CertLoader TwoEkuTsaCert = new CertLoaderFromRawData(RawData.TwoEkuTsaCert, RawData.TwoEkuTsaPfx, "export"); public static readonly CertLoader NonCriticalTsaEku = new CertLoaderFromRawData(RawData.NonCriticalTsaEkuCert, RawData.NonCriticalTsaEkuPfx, "export"); public static readonly CertLoader TlsClientServerCert = new CertLoaderFromRawData(RawData.TlsClientServerEkuCert, RawData.TlsClientServerEkuPfx, "export"); public static readonly CertLoader RSAKeyTransfer4_ExplicitSki = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer4_ExplicitSkiCer, RawData.s_RSAKeyTransfer4_ExplicitSkiPfx, "1111"); public static readonly CertLoader RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Cer, RawData.s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Pfx, "1111"); public static readonly CertLoader NegativeSerialNumber = new CertLoaderFromRawData(RawData.NegativeSerialNumberCert, RawData.NegativeSerialNumberPfx, "1234"); // Note: the raw data is its own (nested) class to avoid problems with static field initialization ordering. private static class RawData { public static byte[] s_RSAKeyTransfer1Cer = ("308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232" + "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101" + "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422" + "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481" + "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b" + "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816" + "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417" + "cbb5a1b360d67998d334").HexToByteArray(); // password = "1111" public static byte[] s_RSAKeyTransfer1Pfx = ("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e040818fdedadbb31b101020207d0048202806aa390fa9a4cb071a0daf25765ed69efe039896036c0f0edfc03ebe35d2a" + "f2f6a5bc9efd907f3b64ae15ac7f61d830e48810aa096ee37fe442b7bfbceeb92e22c25bd5484baf91460be29e06648485db" + "7b10ea92d17983c4d22067396c12e4598541ab989d7beb38bf8a0213fd7c9d49ecd46d319bbb58b1423504cd4145e1b33978" + "41306c5ace9eab42d408e05101911adc684e63a8c8c9579ce929e48ce2393af1a63c3180c52bd87475e3edb9763dff731ede" + "38fc8043dee375001a59e7d6eec5d686d509efee38ef0e7bddcd7ba0477f6f38ff7172ceaeef94ff56ad4b9533241f404d58" + "c2b5d54f1ab8250c56b1a70f57b7fffc640b7037408b8f830263befc031ffe7dbc6bef23f02c1e6e2b541be12009bfb11297" + "02fc0559e54d264df9b0d046c73ad1b25056231e5d3c4015bdc4f0a9af70ac28b7241233ecc845ce14484779102a45da2560" + "c354ec3e01f26d0e0b9a8b650f811d2ffeba95ec1e5cf6be2d060788c1b18ea4ec8f41e46da734c1216044a10a3e171620ed" + "79f7e9dd36972c89d91111c68fd60a94d2aa2a3dbbde0383c7c367f77b70a218ddf9fb4ed7abf94c233ffb2797d9ca3802ed" + "77868d3ab5651abb90e4de9ea74854b13603859b308689d770a62b5821e5a5650ecb23ca2894ad7901c7e1d2f22ef97e9092" + "f0791e886487a59d380d98c0368d3f2f261e0139714b02010e61aa073ee782b1fe5b6f79d070ef1412a13270138330a2e308" + "599e1e7829be9f983202ac0dc1c38d38587defe2741903af35227e4f979a68adef86a8459be4a2d74e5de7f94e114a8ea7e4" + "0ea2af6b8a93a747377bdd8ddd83c086bb20ca49854efb931ee689b319f984e5377f5a0f20d0a613326d749af00675c6bc06" + "0be528ef90ec6a9b2f9b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202" + "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc" + "308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232" + "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101" + "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422" + "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481" + "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b" + "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816" + "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417" + "cbb5a1b360d67998d3343115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414c4c0" + "4e0c0b0a20e50d58cb5ce565ba7c192d5d3f041479b53fc5f1f1f493a02cf113d563a247462e8726020207d0").HexToByteArray(); public static byte[] s_RSAKeyTransfer2Cer = ("308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630" + "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101" + "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2" + "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8" + "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f" + "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45" + "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599" + "a3492c99c9a3acf41b29").HexToByteArray(); // password = "1111" public static byte[] s_RSAKeyTransfer2Pfx = ("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e04080338620310d29656020207d0048202804a94d3b1a1bf43efe3726aa9f0abc90c44585d2f0aee0864b4d574cd2cc1" + "dca4a353b102779e072ed6072d3c083b83974e74069b353ba8ac8be113228e0225993f5ecb7293ab1a6941bef75f7bcb0e3b" + "e6902832be46b976e94c6a0bc6865822ff07371551d206e300558da67cf972d89c3d181beb86d02f5523baa8351b88992654" + "a4c507e136dd32120530585a25424fe40f9962b910e08fb55f582c3764946ba7f6d92520decfc9faa2d5e180f9824e5ed4c8" + "c57e549a27950e7a875f2ed450035a69de6d95ec7bd9e30b65b8563fdd52809a4a1fc960f75c817c72f98afb000e8a8a33be" + "f62e458c2db97b464121489bf3c54de45e05f9c3e06c21892735e3f2d9353a71febcd6a73a0af3c3fc0922ea71bdc483ed7e" + "5653740c107cfd5e101e1609c20061f864671ccb45c8b5b5b7b48436797afe19de99b5027faf4cead0fd69d1987bbda5a0a4" + "0141495998d368d3a4747fc370205eed9fc28e530d2975ca4084c297a544441cf46c39fb1f0f42c65b99a6c9c970746012ad" + "c2be15fbbc803d5243f73fdec50bdee0b74297bd30ca3ea3a1dc623db6a199e93e02053bd1a6ca1a00a5c6090de1fa10cdd5" + "b5541bd5f5f92ff60a139c50deff8768e7b242018611efd2cce0d9441f3c8b207906345a985617ba5e98e7883c9b925ba17d" + "c4fadddbbe025cecd24bb9b95cae573a8a24ceb635eb9f663e74b0084a88f4e8e0d2baf767be3abe5b873695989a0edac7bd" + "092de79c3b6427dcbedee0512918fc3f7a45cd6898701673c9ed9f2f873abb8aa64cec7b8d350e8c780c645e50ce607a1afd" + "bcefba6cf5cebbc766d1e61d78fbef7680b38dd0f32133ceb39c6c9cabd0b33af9f7ef73c94854b57cf68e61997b61393a0b" + "6fc37f8834157e0c9fba3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202" + "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc" + "308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630" + "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101" + "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2" + "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8" + "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f" + "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45" + "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599" + "a3492c99c9a3acf41b293115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a04143cdb" + "6a36dfd2288ba4e3771766d7a5289c04419704146c84193dc4f3778f21197d11ff994d8bf4822049020207d0").HexToByteArray(); public static byte[] s_RSAKeyTransfer3Cer = ("308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630" + "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101" + "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e" + "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3" + "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b" + "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b" + "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459" + "6e27a32e23b3f3fcfec3").HexToByteArray(); // password = "1111" public static byte[] s_RSAKeyTransfer3Pfx = ("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e0408a9197ad512c316b5020207d004820280b1c213fa87f3906cde3502249830a01d1d636d0058bd8d6172222544c35a" + "9676f390a5ef1d52f13fae2f04fe2ca1bcb9914296f97fdf729a52e0c3472c9f7ae72bd746f0a66b0c9363fae0328ad063fa" + "45d35cc2679c85e970c7420ad036012ce553ef47ed8fe594917739aab1123be435a0ca88ac4b85cf3d341d4aeb2c6816d8fc" + "a2e9611224b42f0ca00bde4f25db460200f25fe99ed4fd0236e4d00c48085aec4734f0bce7e6c8fea08b11a2a7214f4a18c0" + "fa4b732c8dae5c5857f2edec27fa94eb17ac05d1d05b321b01c1368231ff89c46c6378abf67cb751156370bbcc35591e0028" + "d4ace5158048d9d25b00e028b7766f1c74ade9603a211aad241fc3b7599a2b15f86846dfdc106f49cf56491b3f6ff451d641" + "400f38fabcdb74a4423828b041901fa5d8c528ebf1cc6169b08eb14b2d457acb6970a11ccaa8fbc3b37b6454803b07b1916e" + "2ad3533f2b72721625c11f39a457033744fde3745c3d107a3f1e14118e04db41ca8970a383e8706bcf8ba5439a4cb360b250" + "4fcae3dbfb54af0154f9b813ad552f2bdbc2a9eb61d38ae5e6917990cbeb1c5292845637c5fed477dabbed4198a2978640ba" + "7db22c85322115fa9027ad418a61e2e31263da3776398faaaab818aae6423c873bd393f558fa2fc05115b4983d35ecfeae13" + "601519a53c7a77b5688aeddc6f210a65303eeb0dbd7e3a5ec94d7552cf4cbe7acebf5e4e10abaccd2e990f1cf217b98ad9b5" + "06820f7769a7c5e61d95462918681c2b111faf29f13e3615c4c5e75426dbcd903c483590434e8ab1965dc620e7d8bebea36f" + "53f1bc0807933b0ef9d8cc1b36b96aff8288e9a8d1bba24af562dfeb497b9a58083b71d76dacd6f2ce67cb2593c6f06472ef" + "e508012c34f40d87e0be3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202" + "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc" + "308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118" + "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630" + "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101" + "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e" + "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3" + "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d" + "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b" + "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b" + "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459" + "6e27a32e23b3f3fcfec33115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414cd11" + "0833d653f2e18d2afb2de74689ff0446ec7d0414f2ca1c390db19317697044b9012ef6864e0f05cc020207d0").HexToByteArray(); public static byte[] s_RSAKeyTransferCapi1Cer = ("3082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d0500301e311c301a0603" + "55040313135253414b65795472616e736665724361706931301e170d3135303431353037303030305a170d32353034313530" + "37303030305a301e311c301a060355040313135253414b65795472616e73666572436170693130819f300d06092a864886f7" + "0d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03e301c37d9bff6d75b6eb6671ba" + "9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6c9d2b4e283ea3535923f398a31" + "2a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4111299f99424408d0203010001" + "a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e311c301a060355040313135253" + "414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d050003818100" + "81e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c5931662d9ecd8b1e7b81749e48468167" + "e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957d653b5c78e5291e4401045576f" + "6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646").HexToByteArray(); // Password = "1111" // // Built by: // // makecert -r -len 1024 -n "CN=RSAKeyTransferCapi1" -b 04/15/2015 -e 04/15/2025 RSAKeyTransferCapi1.cer -sv RSAKeyTransferCapi1.pvk -sky exchange // pvk2pfx.exe -pvk RSAKeyTransferCapi1.pvk -spc RSAKeyTransferCapi1.cer -pfx RSAKeyTransferCapi1.pfx -po 1111 // public static byte[] s_RSAKeyTransferCapi1Pfx = ("30820626020103308205e206092a864886f70d010701a08205d3048205cf308205cb3082035806092a864886f70d010701a0" + "82034904820345308203413082033d060b2a864886f70d010c0a0102a08202b6308202b2301c060a2a864886f70d010c0103" + "300e0408dbd82a9abd7c1a2b020207d004820290768873985e74c2ece506531d348d8b43f2ae8524a2bcc737eeb778fac1ee" + "b21f82deb7cf1ba54bc9a865be8294de23e6648ffb881ae2f0132265c6dacd60ae55df1497abc3eb9181f47cb126261ea66f" + "d22107bbcdb8825251c60c5179ef873cb7e047782a4a255e3e9d2e0dd33f04cde92f9d268e8e4daf8ba74e54d8b279a0e811" + "9a3d0152608c51331bbdd23ff65da492f85809e1d7f37af9ae00dca796030a19e517e7fe2572d4502d4738fd5394ee369216" + "fb64cf84beab33860855e23204156dcf774fac18588f1c1ca1a576f276e9bfbf249449842f193020940a35f163378a2ce7da" + "37352d5b0c7c3ac5eb5f21ed1921a0076523b2e66a101655bb78d4ecc22472ac0151b7e8051633747d50377258ab19dcb22e" + "e09820876607d3291b55bba73d713d6689486b310507316b4f227383e4869628ad31f0b431145d45f4f38f325772c866a20e" + "0b442088cbf663e92e8ee82dd495fba8d40345474a384bb3b80b49ca1d66eef5321235135dcc0a5425e4bf3b8ce5c2469e2a" + "c0f8d53aab276361d9a2ff5c974c6e6b66126158676331fe7f74643fd1e215b22d7799846651350ed0f1f21a67ac6b3bfd62" + "7defb235ef8732d772d1c4bea2ae80c165f0182f547ea7a3f3366288f74c030689988a9838c27b10a48737a620d8220f68b4" + "ea8d8eb26298d5359d54a59c6be6716cefc12c929e17bb71c57c560659a7757ba8ac08ae90794474e50f0e87a22e2b7c3ebd" + "061390928bf48c6c6200c225f7025eab20f5f6fee5dc41682b2d4a607c8c81964b7d52651e5a62a41f4e8ea3982c294a4aee" + "8a67dc36a8b34b29509a4868c259dc205d1e8a3b6259a76a147f002f3bfbc8378e8edd230a34f9cd5f13ce6651b10394709d" + "5092bb6a70d8c2816f1c0e44cd45dfa7c2d94aa32112d79cb44a3174301306092a864886f70d010915310604040100000030" + "5d06092b060104018237110131501e4e004d006900630072006f0073006f006600740020005300740072006f006e00670020" + "00430072007900700074006f0067007200610070006800690063002000500072006f007600690064006500723082026b0609" + "2a864886f70d010701a082025c048202583082025430820250060b2a864886f70d010c0a0103a082022830820224060a2a86" + "4886f70d01091601a0820214048202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906" + "052b0e03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135" + "3037303030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243" + "6170693130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2b" + "c27b03e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec8" + "6aa8f6c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a3" + "36baa4111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa1" + "20301e311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4c" + "ca300906052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c" + "5931662d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075" + "d11957d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646311530130609" + "2a864886f70d0109153106040401000000303b301f300706052b0e03021a041463c18f4fec17cf06262e8acd744e18b8ab7b" + "8f280414134ec4a25653b142c3d3f9999830f2ac66ef513b020207d0").HexToByteArray(); public static byte[] s_RSASha256KeyTransfer1Cer = ("308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e" + "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31" + "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a" + "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d" + "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec" + "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1" + "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33" + "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9" + "ac81cf3e9701baf81efc73a0ed88576adff12413b827").HexToByteArray(); // password = "1111" public static byte[] s_RSASha256KeyTransfer1Pfx = ("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e040829e4911057aa5fb6020207d00482028052e016e1e339ca6a648ab1e152813899bd2ec0de1e34804c33e109cf2136" + "d42edc0d5ff8a005939ec38d4284aa0cfda295e801b701855c3c129e9311dc80b3538ba76d3164d48d83a73949d695f42294" + "75469f262c807767bc5c12bb83b2c4857fa9f8c7c519143136ba93ab93e17ad4b0b63cf6449708e6128425b00eaeae6bc5b6" + "7ff092673c9aabbbb63e90424295f0ae828bcd00f5ad85fe8384711ca5fffd4cbfe57ddbc3e5bb1df19e6fd7640fbd8d4516" + "f8d2d5ec84baca72ac42b50e77be0055dfdbbbe9c6de42c06fc86de8fbfc6231db89b30065d534e76aa851833b6c9c651288" + "c12f87ba12ae429e9bec0b22297c666046355ebd5a54dc7f13a55e0ebd53c768f69eee57d6041263f5bdf1c4c5b2b55dfb9b" + "38171aaed0d21fd5a41e0ef760db42f373c9007e1df47fd79ba9b41528c9c02dffdd04472265763ae94f4e05b86976a2c459" + "093d8e6bb0d0c5da5994fe3edbdf843b67e8e4c4daf59351788bf8b96da116aecbb95d52bf727ff10ca41340112f0bcb41e0" + "b8373a6e55727c745b77cf1944b74fa447ed0a6d93b8e43fd6e4b4b3e0d49d03ee2ee12d15519406c49a4c1be70de5171c93" + "d056e9f47b8a96d50f01873be4c596590f1247a2f2822dea9339fa87dd49545b559e0225ab738ecc0b054155749670d412be" + "472d13dfb0a8c8f56b3c0be1aa0d9195ba937b0c2119c702a0be1f83e1b4a77375ed1654e3dcf6b8ce119db3ac7cd440369a" + "b0b964e0b526b865680015cc3046a20badeaca4543ce65042ff5eb691e93232754a7b34fd8b6833c2625fdfdc59d80b3dcb4" + "ce70d1833ecf6344bb7331e46b71bb1592b6d814370548ee2b2f4df207696be87d2e1e0c5dc0ca528e5a231802cbb7853968" + "beb6ceb1b3a2998ecd313174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202" + "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8" + "308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e" + "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31" + "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a" + "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d" + "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec" + "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1" + "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33" + "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9" + "ac81cf3e9701baf81efc73a0ed88576adff12413b8273115301306092a864886f70d0109153106040401000000303b301f30" + "0706052b0e03021a0414282ee1780ac2a08b2783b1f8f7c855fb1a53ce9e04143fad59471323dc979f3bf29b927e54eca677" + "7576020207d0").HexToByteArray(); public static byte[] s_RSASha384KeyTransfer1Cer = ("308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e" + "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31" + "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607" + "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b" + "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4" + "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680" + "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09" + "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7" + "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef").HexToByteArray(); // password = "1111" public static byte[] s_RSASha384KeyTransfer1Pfx = ("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e040856d7d59810ce8b17020207d00482028082012797edb5f74429bb6b91dd1e24aa32a19b89d92fd486e826773a7a11" + "03a9b49d98c6b7e97d411d19b44cd79559964f31cb6f0443c70d687c390d31c656ee3887391ae1735c142d891ec8337c5dc4" + "d6b5a4f09400a4cc35dd8dbde831f7625b7afedf4990294988b0b32b2889c97cd85c2568ffef332be83232449dd4083a43d4" + "89e654520eb922239379b5e9f5dfc1e64972339dee27dfdd874e2ee2b85f941f3b313ab881571c3a5a9b292d8c82d79d74a0" + "2d78dd5cfce366b3a914b61b861b35948757d137e5d53589a0fa2f1b4d06ee6b4aa4b8d3f526b059637b236ceb2de128d7bd" + "f91c12612d09e1cb4bed1b5e336fb56424b68dcc6d6cd5d90f666047c8b181526a60622027d322db0172046c23e84a3c725e" + "45ce774df037cafb74b359c3ec6874dce98673d9f7581f54dcb6e3c40583de2de6aaf6739bba878362e9bfab331cab2eb22d" + "3b130dec4eedf55a7ed8d5960e9f037209f9c1ef584c6dd5de17245d0da62c54420dc862b6648418d2aa9797f86a2cd0ecf6" + "abcbeb16907d8f44021690682a4e1286cd3f9aea4866108b3c968cf4b80a39c60436079617346861662e01a5419d8cebe2c6" + "e186141e42baf7cfc596270dbab8db03da9bd501daa426e24aa2d8ccf4d4512a8dce3ae8954be69b5c3a70fac587ac91ad97" + "fb427c8118659b710b57183c4fd16ffd276834e2fe45d74e175f3f5077783cdd7668b4e87217512ceb7f3e64715ba22bbab7" + "0d1b3485820c16304758cf1dd0b806d801f1185bb14d12f2c147ec65b95088077dec23498ebe40a952727c559c7af5cf20f1" + "f491f4123db093dc1a67014c3db46c11c7d5833b15167c91138eba6b4badf869aefba5fbea523a5ad02bb676db6039e7aabd" + "44f0702d59cf3d1ad9bb3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202" + "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8" + "308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e" + "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31" + "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607" + "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b" + "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4" + "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680" + "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09" + "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7" + "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef3115301306092a864886f70d0109153106040401000000303b301f30" + "0706052b0e03021a041429bd86de50f91b8f804b2097b1d9167ca56577f40414b8714b8172fa1baa384bed57e3ddb6d1851a" + "f5e9020207d0").HexToByteArray(); public static byte[] s_RSASha512KeyTransfer1Cer = ("308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e" + "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31" + "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f" + "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09" + "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3" + "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2" + "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e" + "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637" + "91784d778663194097180584e5e8ab69039908bf6f86").HexToByteArray(); // password = "1111" public static byte[] s_RSASha512KeyTransfer1Pfx = ("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0" + "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103" + "300e04083a0e344b65dd4e27020207d00482028014464df9f07d2cb37a28607570130de5877e829e759040976866afc831db" + "4d2741734ae53ea5eb80c1080dae7b0a2acddabd3d47b1ed5f3051455429308f3b7b0b48c5a4dbc5d718534472c746ce62f1" + "bbb8c5d178c1d3e91efdbd4f56569517bcadf3c81dbe4c34746194e47bcf46b74cd1880d7bd12d9b819b462fbcf6f51f3972" + "2858c9b9af8975bfefd7f007928b39e11d50b612761d03e566b992f92e9c9873d138c937fc43fe971db4c8e57b51aeef4ed0" + "022ec76c3bb4bd9f2395b99585449303a6d68183edf6e5dda1885531bee10b7cf6509390f4ee6a37ed2931d658548bd6390f" + "a7094fdf017166309074c00581d2b7dcaaee657f9c48e08edf636004dc5e60486dd022c45058700fe682472b371380948792" + "74c2a20dd9e07e149e7ab52157db748160ad81f91019297baa58ce68656b0b2f7c9ac88b3da6920c2a5eab7bcc2629974f8a" + "6c8bf33629af05e4e34d5d24393448e9751b7708f5915b0fd97a5af4dd5a37d71b18b6526316cbc65b1c6af8a6779acbc470" + "2381f027bdb118cb84e9005b02a8bd2d02365d280cffb04831f877de7bd3d3287f11beed8978a5389e2b28317eb90569781f" + "94f66f672736a09b4a7caeaaefd1909f2d20255df51512dbd08ec6125455d932b626bdfd3c4f669148fa783671f90b59ceff" + "560c338f92cbe8bf7fbab4db3e9b943effac747eb34f06bd72aee961ed31742caa2a9934a5fe4685677ecbca6fb1b1c0b642" + "b4f71d55d0e2cb1dc10ce845514090cc117a875c4d10c0ce367e31091144eacd7e600792d61d036bde020e3bb9a004a7dd1a" + "cf03541b6fff3bcef4c30df05d98b75688320685261b2b34813407b20a7c92a04eeb46cb7e618a6ee32154728ba6735668f4" + "11abece4ba07426a394b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e" + "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074" + "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202" + "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8" + "308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e" + "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31" + "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30" + "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f" + "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09" + "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3" + "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2" + "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e" + "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637" + "91784d778663194097180584e5e8ab69039908bf6f863115301306092a864886f70d0109153106040401000000303b301f30" + "0706052b0e03021a041401844058f6e177051a87eedcc55cc4fa8d567ff10414669cb82c9cc3ceb4d3ca9f65bd57ba829616" + "60d9020207d0").HexToByteArray(); public static byte[] s_DHKeyAgree1Cer = ("3082041930820305a00302010202100ae59b0cb8119f8942eda74163413a02300906052b0e03021d0500304f314d304b0603" + "5504031e44004d0061006e006100670065006400200050004b00430053002300370020005400650073007400200052006f00" + "6f007400200041007500740068006f0072006900740079301e170d3136303431333132313630315a170d3339313233313233" + "353935395a301f311d301b06035504031314446648656c6c654b657941677265656d656e7431308201b63082012b06072a86" + "48ce3e02013082011e02818100b2f221e2b4649401f817557771e4f2ca1c1309caab3fa4d85b03dc1ea13c8395665eb4d05a" + "212b33e1d727403fec46d30ef3c3fd58cd5b621d7d30912f2360676f16b206aa419dba39b95267b42f14f6500b1729de2d94" + "ef182ed0f3042fd3850a7398808c48f3501fca0e929cec7a9594e98bccb093c21ca9b7dbdfcdd733110281805e0bed02dd17" + "342f9f96d186d2cc9e6ff57f5345b44bfeeb0da936b37bca62e2e508d9635a216616abe777c3fa64021728e7aa42cfdae521" + "01c6a390c3eb618226d8060ceacdbc59fa43330ad41e34a604b1c740959b534f00bd6cf0f35b62d1f8de68d8f37389cd435d" + "764b4abec5fc39a1e936cdf52a8b73e0f4f37dda536902150093ced62909a4ac3aeca9982f68d1eed34bf055b30381840002" + "81804f7e72a0e0ed4aae8e498131b0f23425537b9a28b15810a3c1ff6f1439647f4e55dcf73e72a7573ce609a5fb5c5dc3dc" + "daa883b334780c232ea12b3af2f88226775db48f4b800c9ab1b54e7a26c4c0697bbd5e09355e3b4ac8005a89c65027e1d0d7" + "091b6aec8ede5dc72e9bb0d3597915d50da58221673ad8a74e76b2a79f25a38194308191300c0603551d130101ff04023000" + "3081800603551d010479307780109713ac709a6e2cc6aa54b098e5557cd8a151304f314d304b06035504031e44004d006100" + "6e006100670065006400200050004b00430053002300370020005400650073007400200052006f006f007400200041007500" + "740068006f00720069007400798210d581eafe596cd7a34d453011f4a4b6f0300906052b0e03021d05000382010100357fbe" + "079401e111bf80db152752766983c756eca044610f8baab67427dc9b5f37df736da806e91a562939cf876a0998c1232f31b9" + "9cf38f0e34d39c7e8a2cc04ed897bfdc91f7f292426063ec3ec5490e35c52a7f98ba86a4114976c45881373dacc95ad3e684" + "7e1e28bb58e4f7cfc7138a56ce75f01a8050194159e1878bd90f9f580f63c6dd41e2d15cd80dc0a8db61101df9009d891ec2" + "28f70f3a0a37358e7917fc94dfeb6e7cb176e8f5dbfa1ace2af6c0a4306e22eb3051e7705306152ce87328b24f7f153d565b" + "73aef677d25ae8657f81ca1cd5dd50404b70b9373eadcd2d276e263105c00607a86f0c10ab26d1aafd986313a36c70389a4d" + "1a8e88").HexToByteArray(); public static byte[] s_RSAKeyTransferCer_ExplicitSki = ("3082033E30820226A003020102020900B5EFA7E1E80518B4300D06092A864886F70D01010B0500304D310B3009060355" + "04061302515A310D300B060355040813044C616E643111300F060355040713084D7974686963616C311C301A06035504" + "03131353656C662D5369676E6564204578616D706C65301E170D3136303632383030323034355A170D31363037323830" + "30323034355A304D310B300906035504061302515A310D300B060355040813044C616E643111300F060355040713084D" + "7974686963616C311C301A0603550403131353656C662D5369676E6564204578616D706C6530820122300D06092A8648" + "86F70D01010105000382010F003082010A0282010100D95D63618741AD85354BA58242835CD69D7BC2A41173221E899E" + "109F1354A87F5DC99EF898881293880D55F86E779E353C226CEA0D1FFCC2EE7227216DDC9116B7DF290A81EC9434CDA4" + "408B7C06517B3AFF2C9D0FD458F9FCCDE414849C421402B39D97E197CA0C4F874D65A86EAD20E3041A0701F6ABA063AC" + "B418186F9BF657C604776A6358C0F031608673278EFD702A07EE50B6DC1E090EEE5BB873284E6547F612017A26DEC5C2" + "7533558F10C1894E899E9F8676D8C0E547B6B5C6EEEF23D06AA4A1532144CF104EB199C324F8E7998DB63B251C7E35A0" + "4B7B5AFFD652F5AD228B099863C668772BEEEFF4F60EA753C8F5D0780AAED4CFA7860F1D3D490203010001A321301F30" + "1D0603551D0E0416041401952851C55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D01010B0500038201" + "0100BB7DDDC4EEC4E31163B84C5C3F4EA1B9314B75D4CCCA8F5339503DC6318E279E73826AD77AC6EA4344F2905D8792" + "83D867A66319E1EA383B70CE997A98D545FE258E38C577554E3BBDF42349B98BED9C94B7CE55D51F740EF60ACC75D017" + "F3D0D1438F8F86B2453F2308279521EE4AC09046498F60ECEC8867E7BF011C882A514BF85F6C915A70E0383AB5320034" + "19A107A9FFEDBF34681AEEE57DF6A3DB3759D605A9269FB694D8EA56A90740529159D725BFD70C9141A38B98D4E88CDC" + "31124ABBB4C3D3D49C220CCB6F2F94176B8225A0E2ADDB0F4A72E6B021601CD297AC45A0CAB95EBAC4001C8167899868" + "3188DB9364AAD52D4E28169CC898B621FF84").HexToByteArray(); // password = "1111" public static byte[] s_RSAKeyTransferPfx_ExplicitSki = ("308209810201033082094706092A864886F70D010701A08209380482093430820930308203E706092A864886F70D0107" + "06A08203D8308203D4020100308203CD06092A864886F70D010701301C060A2A864886F70D010C0106300E0408101C5A" + "3E2DBE2A9102020800808203A0F58476F5E4741F8834F50ED49D1A3A5B2FC8C345B54255C30556B1426C1BA1D9EE4440" + "CD63CD48557B7BDC55D877D656183E2815DEDE92236E036E0D7FD93022174EFA179A85EF76DEE10950EE3BEB004FB118" + "C58D4372A319575DB129F5912B385E63E1E83DC420A8FC8C23A283977480281EDDD745D97EC768328875D19FE414D7D9" + "9D3B0AAA2FBA77346F82E4E1357C54E142B2F5E929CBD6057801F49ED08A8BD2456918CCEDAD6DAD9A7281C4EFD2FCF5" + "6F04EDC5E62E79741024AF8BE401141AA9A9CE08F5D51D4636D8B25F9B3C59B4BC2DD7E60FBABA0A7E8FE15EAECB7221" + "3BC22D8CE56987427B41A79333FB4B9BC5DB6E79C2AE4E954F975C343D155C5587BD7206414B9C0529D00C6DB1470C33" + "A51D2A9BBDE5CC2352C61B0FB9945487FDB0E26981426BE7CCF44CF494E695D4760060468B7D23BA3C6F9B1762AC4B3A" + "428B23A36F275F3FDFD7BAB236197C7C7FB6466A11B05DB39F947FB19EFE9BFED2B18308E2BBD0AB00AA399508194CB2" + "1073B1B278BE389A8AA843B610B439AFA056A0EC81EBDF4061D2AB87C9CB840C3E6B92BB2FC30815D5744593862CC34A" + "EF1C4B7BBCF640CBA2D1E15E13D3B571FD3C403BC927812B291E53EAE6721C994E343148C10A16053AE560A55DFA5695" + "33CA35D83D81643CC7788E7F94C6592F99C09AFB770E9FE1380A1212A646A936BE531BF85F89D19EF57C180E8E3F1F4F" + "BD266032095862E3A0F8394E93CEFF2B8ADAD374DFCB8A041DB498618D1D71765EFD1CD5B024AC13B9FF0F96F975B443" + "08C14AC60965082CC409AE43D033512CF1B83458D475D2E06A49131894F1D4BFAF5FC4CBADA8566B6312E8DA31D8A397" + "273BE77B8395F4CAB4428B22DFE18FD4365C134B7724220D2DCE31938EFCF8E4DFC321E02CF15476BF5EB675F2055205" + "9662166A4549904BC6A5E4B8353C43DAC225317F4B4FA963C900F0B0D0E7FC854BE91A1CFF330FE77B03776EABD0326B" + "0FB37AC5176CF82530960F423B13299E037285C9324E0A872414ECF35735F58463506EBFB2CC91D790FC0D67E2714287" + "960C68FB43A7EE42A14F5397F07E055E75EE4F7D047634907702EEC8ABB08D82C82CEBE2B042B1F20367DFDB839B82AF" + "88F72272AE91DA94CD9B334343196889381FE307A76BE0B627EE32D827582A7CD68BF467D954805030753FA8DABFCC21" + "E68A77E2A76F9E95E61A2FBCA1C8FFC2CE272E9D125E5C65759529BF3FDD2E28722EC9B7B57BD9819BAAC01556002D88" + "3B8BD842C3EB3BCC4A54B4D0B1DB32ECEBA8DD668D67C859A6EB0BAE293082054106092A864886F70D010701A0820532" + "0482052E3082052A30820526060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D010C010330" + "0E0408482E476C7712FD7202020800048204C8AF5357D64578320D963917F44B2B7714334AAE6571554F03A599913275" + "4BA03892316159385225C4EEA7C958091BC8A32A9433AECA3A07F791ACE431217F0DFBD53DC15D257069B99DA04EF719" + "892004FD307E151EBB359C1D69AE8FF78A1CC1654470B0862CDAC1AED521608C29AA8D30E81A4015D54F75421B9BDB29" + "5036D79E4535F28D4A2ABF4F203BC67065A709AEF6EAF4D6A3DC7387CB3459D82399F4797CE53FD2BD0A19B1A9566F74" + "246D6B6C50BD2777B6F6DE1A8C469F69D7EBF230018D56DF4C1764862CD982E81F56A543DA4ADB63EF8612A1BB561471" + "56035541B0B41F06BBE2CD47DC402A75023558205870060438CF99D8BFC7CAADDE0583311FE4B854051C83638420BC5E" + "93F999E67EDBBC266F519609E2BE9FC1BC3C7FEE54DBAB04DAC8A94BB347F3DC28DDAB7D28DD3BBFFB44C84E6F23A8E0" + "1CAB36382723DB94CD8973A303D8D4C7A22B9F811C07ED9A78E06135E0426FC93BB408F1DC915DF4ADBF048D22C201D8" + "0FDC0EF942D1E2AC0F39F8A95BA849C07BB0DA165B3F0317478870F704B8A34B7D5816BC4F8CA0C6BDB5346F2211416C" + "79D7117AD1B86E44E0BC0C3793F9895638E5B7A2A5B957E0E691819AC7FA1F05E8D05ED99E4E286C96E3E31DF99633E8" + "CB73CA135109AE727CB047641726A1599492B6F3E8E62195A79239279B2A9FBF47B31FEFF3C20DEC2DFBDB0CE98B183D" + "BA773561DEE404BA1A5BEF5AB9729DBE22FB1C17EFD4D3AC81F04F49F9855CEACECB202090A1290C10E9D676F0658F3D" + "E4C43DCD5A17B88881893DA87060C5F56D5CC9A92E6B1A47A6D16FB32C09925606F6D5C7CAFBC7A82D8E441A05DFBEE0" + "BEC92D89264B62D5DECC342D29D9A7727BBDE4E63EEB7CAED7C76953F6AC8CB570619C7607B753FD46889C76D29C9AC6" + "6F56CB3848323FA9CD16578EA5C6D876AE63D95F65E2CDEF68A1CF3D2FC3DF91D0055B0CDBD1510E291C0E7AC6EAA0D2" + "AB5E8FAD44108C94A592251447926DB7139BC2A433D61711C6DA5EF82A8E18CEBF99AF753E33FFF65126B7D3D3D09FF0" + "C50EFF7822FA8797BAC52383B94E8FE602E62577994ACA6A2150F60A31CA0E79FE6DF3405D6918EADC2231558FB29045" + "034EB9DA9FB87BD71996C6AB6EA71A70EBFBC99BC292338A363176516C14EC92E174C59C6BE82F5BC0296525109C9A7F" + "C9D9E654955992A5C9EDFD39ED9889BEAF105B2EF62B041789F20A6AB26563FCFA1A1482EE2A20E8C1A2F0931ACBA7F8" + "756EE4C9119D29817ACA7D2B81FE736FD7A33D20EC333AC5123D29345647B734DB24B5C56B4576ABBF9B02F782DDE0B4" + "BA277080F28F3D86DEC35F0F19B2B5DB0BD7A59B7C4B2BAE08E8584449BD3685F371F6A24F5F91EA6843DC6ABA89976E" + "589511EB23A733D23F6CE076C952E9E7190ED78D5A34387F93418A87CB02270941F19DD35E1DB5836E67296A7F28A5EB" + "8F32DA73EA7A47D5CEB292E767468CDF938A44B3CEEE6276A34705606A8F7496D7310DA1A0468A604B8A9E7AB50450A6" + "DFE0C4540CEA058CD7919E823D8A32FB811C6BF8754C65D7A9723018ADE95AED5C30978A8DBA185CF0BA36346456CD3E" + "15C511FAD71B445DDFA7C5455A3597FE536E3BB87518C0725D6BE673D05DC5E74B4FF442711D242A37D0CCB88E6D19BD" + "6B7299207D7036EB87D5E86189768CB14AE4F8886BB5AB7864BDA9757D0C26BFFF3FAA4001258557D394313125302306" + "092A864886F70D01091531160414080FB9AAB81BD67FD85C2186B359054CEB13D2D730313021300906052B0E03021A05" + "0004142C205F0B1E9B99B0ED14E83F13D84BC683F66D3B04080D22E45D6A657CC602020800").HexToByteArray(); public static byte[] s_Rsa2048SignatureOnlyCer = ( "3082032C30820214A003020102020900E0D8AB6819D7306E300D06092A864886" + "F70D01010B05003038313630340603550403132D54776F2074686F7573616E64" + "20666F7274792065696768742062697473206F662052534120676F6F646E6573" + "73301E170D3137313130333233353131355A170D313831313033323335313135" + "5A3038313630340603550403132D54776F2074686F7573616E6420666F727479" + "2065696768742062697473206F662052534120676F6F646E6573733082012230" + "0D06092A864886F70D01010105000382010F003082010A028201010096C114A5" + "898D09133EF859F89C1D848BA8CB5258793E05B92D499C55EEFACE274BBBC268" + "03FB813B9C11C6898153CC1745DED2C4D2672F807F0B2D957BC4B65EBC9DDE26" + "E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33C8B57248B3D5E3901D8A38A283" + "D7E25FF8E6F522381EE5484234CFF7B30C174635418FA89E14C468AD89DCFCBB" + "B535E5AF53510F9EA7F9DA8C1B53375B6DAB95A291439A5648726EE1012E4138" + "8E100691642CF6917F5569D8351F2782F435A579014E8448EEA0C4AECAFF2F47" + "6799D88457E2C8BCB56E5E128782B4FE26AFF0720D91D52CCAFE344255808F52" + "71D09F784F787E8323182080915BE0AE15A71D66476D0F264DD084F302030100" + "01A3393037301D0603551D0E04160414745B5F12EF962E84B897E246D399A2BA" + "DEA9C5AC30090603551D1304023000300B0603551D0F040403020780300D0609" + "2A864886F70D01010B0500038201010087A15DF37FBD6E9DED7A8FFF25E60B73" + "1F635469BA01DD14BC03B2A24D99EFD8B894E9493D63EC88C496CB04B33DF252" + "22544F23D43F4023612C4D97B719C1F9431E4DB7A580CDF66A3E5F0DAF89A267" + "DD187ABFFB08361B1F79232376AA5FC5AD384CC2F98FE36C1CEA0B943E1E3961" + "190648889C8ABE8397A5A338843CBFB1D8B212BE46685ACE7B80475CC7C97FC0" + "377936ABD5F664E9C09C463897726650711A1110FA9866BC1C278D95E5636AB9" + "6FAE95CCD67FD572A8C727E2C03E7B242457318BEC1BE52CA5BD9454A0A41140" + "AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC94F7E3C7D476F29896224556395" + "3AD7225EDCEAC8B8509E49292E62D8BF").HexToByteArray(); public static byte[] s_Rsa2048SignatureOnlyPfx = ( "308209E3020103308209A306092A864886F70D010701A0820994048209903082" + "098C308205BD06092A864886F70D010701A08205AE048205AA308205A6308205" + "A2060B2A864886F70D010C0A0102A08204FE308204FA301C060A2A864886F70D" + "010C0103300E04083EF905F0EA26FBF7020207D0048204D82297B5546DA6CC49" + "BD8C1444E3FE1845A2C9E9BDB8B83E78235DF4ADF7A97496A62D31D4EEEB76B0" + "71C0B183ACC3663272F88CF4F31E2E00D76357C0A051B8D6E0BB0BCF4CCDD064" + "CCBAF546EABA80DA56CD11FE952C61154792559D65F26B0476CF7A5FDB8CC794" + "B89F6ACD50003459054FE82C48D8791B226A0EEEC01F048AC3CE716C9F3BB313" + "D64BEBBF0037D83133DD9C15D04F15BB11652D793B613A68AFE580245724E5D1" + "110040B332B5C39BE04086BA4DFC58E905BC2FE8B3C696181E2879AF197EE24D" + "91D8AD67013F14C4864C8D0FB19C134B766CF3E48B8C9E363A11EB19F1E82E74" + "D25EDD96517D64A94314B40C11651030D561E742E63856E8D1A3EE9FDFD6CF64" + "7140CFC354AE7EA1D14C157C2985F82D54296F7D3DE456AF7513F5F30A0421E4" + "3A9DAD6DF8A2BF69005B35CA8066F80755D848DA73EF03BC0CC129C5799911D9" + "3A1ED43F8E76732AF56FD62DC6D0B0DBA6AAC6DCDE77D0E8AC9F6A5EB5A02B61" + "BC477706D4F1873240AB45E0291EF21E6034D48F1AE8EB139DE7ACD8B8A821E6" + "70B395C3EC4B0E75C34BF0067F052FCED835CAC1F17C3FBEA2FC9FD281FCDE21" + "D5B27CF31A07E90164A979ACEF0E1C67DBA6C33082E9B189D4BDA2D2D504776F" + "455843437BDF10D4AF48639EC03344BCC36EFEA7CDE08D7F94DDEAF98BCB5D65" + "207AE0C349EECE3032DE19F3B337F29A3457AA0AAF4306FA8301619AB01B7235" + "BE16CB93728E142DAA6C1CBBCC5BD82D913596994DA40FB916CF2DB5FBCC20CF" + "E893DC62BBC5FC59E00BC0A704A9DB25BBF9291971F2377FC1A20F2C954869DB" + "6FFCC90C625AABE97ED4CF7C0209D39AD780003C437152D636ACB3B484C46885" + "DC1584733D2153A3F9B968F12CDD5937CDF9DD2581D72EE67C83AE2530197AA7" + "C6110613BEFF0B75E586C28394EA8EBCF7F9DB133295B33DC86C8DBA92BF8BD1" + "ADCAF8D2CD2E018B08D59FF1C30A13484AB11468F7DCEB1FE53A6DAF309B0510" + "7772CB735314A5B2F053E60A653F0496BCB9CADF5E50339A4D2EF2382056B768" + "558EB9230D996C636E6D29664F92F70A088DE3EE4EC4BBD8A9C4C98C7892D122" + "28806622B87E581A321AD835B8F4B964A17B5BE6D9DA50133D494732A41884E2" + "9E891FE2D40ACCFD585C8BF626C1E8A412D2EE7CDE060E2CCDA826BF79D80F1B" + "F6B8400473BCE0C19D03ACF55D1FAA994C04A8CD11D49743B1F45F48DFFDD701" + "18B5FA82ECDF67714F5DE5D3D3DDDCB76ED0EA6A6E151665A4AA351DB1A99F8C" + "7502D3795C2C358CCA589C390C1F4810615130B91BA42A85E77FA37197E1B083" + "FE1246B067C6444D49B369D45B130A6D7B463C3F0459EB41D68009CABD2F5C60" + "49DB706FA742C9773FB5791AF123FBE485E05F87759ADD25281BE337B6095EC3" + "4EFF9FC692798FB4217EF4B2B59902D930F28181933FAA278C041123CAE3CA63" + "6DFD3AD4E04EB751A30D50C26288EA4D01C7B323E4FD6387F88E020BC433BF60" + "C4406398C44EA5C7A6EB24134B0811E4F94DFAF5553172306FA5543C254E7E04" + "DEEC84DBF9FAF7BFEA8D61E094CBB18DD45C5BAB9199DD719F9A305E205605CC" + "671DCD566FEBA2C8F4C1A445625C4F42D1CFE32087F095591798D1D48DA46DE9" + "230F5102B56A1EF879D48936D5331D6B3D9F1B564CF08FD3C641CFF3B02CB4FC" + "8995E5EC5DD1D183704940C02DEA7430FD594E54800DCC74B7732731C63FBBA2" + "A2F6DC031174390A74781D352B09FB4F318190301306092A864886F70D010915" + "3106040401000000307906092B0601040182371101316C1E6A004D0069006300" + "72006F0073006F0066007400200045006E00680061006E006300650064002000" + "520053004100200061006E006400200041004500530020004300720079007000" + "74006F0067007200610070006800690063002000500072006F00760069006400" + "650072308203C706092A864886F70D010706A08203B8308203B4020100308203" + "AD06092A864886F70D010701301C060A2A864886F70D010C0106300E04087CB7" + "E0256AD1AD80020207D0808203800C21CEBEF9F3765F11A188B56702050E3DCA" + "78AA27123654D066399DD56E62187C89A30940B5B63493950EEFA06C04B5CAF0" + "329143AF30EE0B47406E49D4E6241817986F864780B743B58F03DF13523F5C01" + "C889046356623AFA816B163E57A36672FAC9CA72294B2A17F75F5ADB1A4CBDB7" + "B3F5C33C643DA0CC00CB79E54FAB25D1881B81C03BA5762BAA551A7E8BA38144" + "353B07285B288BC2747F75B7AF249040C338CFC585D0B1CECFED46BCAE7FAF09" + "60BB3EE996E30E626CB544A38393BC7DFDB7A27A21A6CF09332B544F448DF5B3" + "31E000F7CCD5CE5C8E8765A2339919C713352FCD30FA52B994C25EA95E548C4B" + "5EC23B3BDEC7342D0676B9227D3405758DBA5BD09F9253791FAA03F158F04848" + "D5073DD240F466F57770353528B3AE83A626F33D05BD1BBB4E28CB067FFAA97D" + "B4C79EEAAFB4B30BE738C1AA5DB1830B3968CDF6BAF778494AE40EF003DCDA54" + "486E9952EB44628385E149C348E0E431928B85608622B994CF43433DA9C19482" + "360121560E53E85FE7CBB7C31E27AD335BC247F284EAC3CA94C30DBB4DF2AB02" + "DF1154626838240213D910D5B7476A025CA7565CECBA0051320FC7EECD6C74FF" + "505566F75804D1E2BD2B0181B235CE911EAD9260C0799C817F956AE290E00EF0" + "997F7B6BD059B315915D580CF0C019A23A6D4993F6E8B8106A1AB6CE1991B609" + "1B42B6D33EE01EC96CB475430365E9C710C5EB4C6010260D12108022449F7E6D" + "1A2F28838304DB2A60B9FF714FC887579A4CDC139DAF30A18D3910D82313CCB1" + "FA43A8930E0F10DE24652AC1E5B797084BEBDB8AB5FA6DCE03E44ABF35EDEB1A" + "FFEAD3F7C9CB342CCA2882D945EB52C20DC595FA10161866EB9426281CF13341" + "311B59FDE8E69F9B853117740D92F4AC1B2E4597D41B8A097E1DAA688FFF1C5C" + "846DF96CA75224EC26F4FF328164F5D1EC06B697211BDB42E6C97EB294A5798C" + "0FCE6104C950A5207F74EC0DED8AEE10463EF2D9ACD7473D2BE48EBBF0A550B9" + "AA19A465147B378B078229E8804918136633D7FCE5340AC61A1418D7D9BB18D1" + "98B7B7866C4D7DC562B1F93F3F322484BDDCEB23680B8EB9904EC783D5CD7177" + "CFE9CA9D1893104E97760E871DE0907D4BDF6263E7BB0F47414AF31E377C7447" + "B881E68AE3E80D06597F12D5EF5ED861D055D494D89F04A70800DA3FD4E53877" + "87FBEED7B772E3A24E7F4832A956FEC0C81847C68373ED4760ABF542F77DC794" + "249519BDDF5F846EB8C5078BCC053037301F300706052B0E03021A0414461F5B" + "19C6933240012EFEB95F734C648CCD13460414FA1743400686D25BA1CB28D736" + "F2B1ED97699EA4").HexToByteArray(); public static byte[] s_dsa1024Pfx = ( "308206EE020103308206B406092A864886F70D010701A08206A5048206A13082" + "069D3082043706092A864886F70D010706A0820428308204240201003082041D" + "06092A864886F70D010701301C060A2A864886F70D010C0106300E04084AF212" + "89D5D7E2E702020800808203F0DECCF218AC91F26BAB026998AB77C7629D20DB" + "E2FB7022A3C4A1CECD743C0F932E944AE229DAFB61AD76C4DEB6995DF4F4BA01" + "2DBAD5C63A4C846E0807FCA0BC4A162CDFBAB4B3C4D304F473B3ACC1D268436E" + "F537DAE97ECC3C634C8DF2A294CC23E904A169F369021A0C024A03DE98A65B0F" + "3F14D6910525D76AD98B91E67BB7398E245CF48A4D2A5603CFCCF4E547D7EDAB" + "669D9A8597C6839119EB9FD932D1E4BA8B45D3317186CDA2EFF247BCFD64A5CA" + "ED604BF7033E423CC21CEC6454FE3B74E03A26C51A1C3519CE339FBE9F10B81D" + "DF6A0AAB4F8166D90B6F52B3439AB4B5273D0A506E3E01869F8FEBD1521EF8E5" + "BFB357FA630E3C988926EF3ACC0A0F4176FE8A93337C1A5C6DEAB5758EC2F07C" + "11E8B2495ECDE58D12312CCCA2E8B2EE8564B533D18C7A26A9290394C2A9942C" + "295EBB0317F5695103627519567960908323FFE6560AD054C97800218A52F37A" + "DDE4E7F18EF3BF3718A9D7BF57B700DBEB5AB86598C9604A4546995E34DBABBB" + "6A9FB483A3C2DFE6046DFD54F2D7AC61C062AF04B7FBAC395C5DD19408D6926A" + "93B896BFB92DA6F7F5A4E54EDBE2CFBB56576878150676ADB0D37E0177B91E0D" + "F09D7B37769E66842DD40C7B1422127F152A165BC9669168885BA0243C9641B4" + "48F68575AA6AB9247A49A61AC3C683EE057B7676B9610CF9100096FC46BDC8B9" + "BAA03535815D5E98BA3ABC1E18E39B50A8AF8D81E30F2DFD6AF5D0F9FC3636AB" + "69E128C793571723A79E42FC7C1BD7F39BD45FBE9C39EEB010005435BEC19844" + "2058033D2601B83124BD369DADB831317E0B2C28CE7535A2E89D8A0E5E34E252" + "3B0FCEC34FF26A2B80566F4D86F958F70106BF3322FA70A3312E48EAA130246A" + "07412E93FDE91F633F758BC49311F6CBBAEC5D2F22AFCD696F72BC22E7DE6C00" + "3275DFEC47E3848226FE9DBA184EA711E051B267C584749F897EFE7EAFD02F1D" + "BF3FD8E882474CA1F45509EF2E7B82F35B677CB88ED42AF729848EE2B424B0CE" + "2E9AAC945BABA550C20D5B25075A30FE70D8CAA5A527A35F1DF17BCCB91930C1" + "7120C625667120E0806C2B51EDFF540F928BD555FB48DBCB83CCCE0C385E78C8" + "65BE715AE6F8BE472E5FC187EBE3FEFD8D7FE62D4DB2EE61F42D24D81FAA9179" + "0FB17E8EBC8E219B6F9E039F5AB3BC4870821D474B36C8F8D0583D9DC06E4383" + "D03424420B8C8B26276877166A0F51E22F0D8FA60A070CFBD47EAFBC717C879C" + "B5A1EA69C4C2A38F26A1EEF96A0C32BFCECCE4EA97E90A425066B1DD0891353F" + "766EB9F2BFA2563A815DAF3639EBB147E1E8757A6BFAB902C4A8F037AD47E03F" + "AF2E019FCF6CA7430BDFEA4B45B28ED746BB90E09BEF7B370A75E7924BBA0920" + "25FE654A9A197A5B8BBBE43DC7C892FF14E75A37EB97FC489AB121A43E308202" + "5E06092A864886F70D010701A082024F0482024B3082024730820243060B2A86" + "4886F70D010C0A0102A082017630820172301C060A2A864886F70D010C010330" + "0E0408ECB4D1550DA52C6302020800048201509322DC0193DD9E79ADAFD38827" + "AD6DE9299327DDDF6E9DF4FB70D53A64951E4B814E90D2A19B3F4B8E39A2F851" + "A3E5E9B9EB947DD248A3E5F5EB458F3323D4656709E97C6BD59238C4D1F26AB6" + "7D73235FAE7780D98705957B6650AC0DE3E2D46E22455D0A105D138F16A84839" + "14EDDF5C518B748558704ED3AE4A8C4914F667BBDE07978E4A4FC66194F6B86B" + "AB9F558EDE890C25DFB97C59653906CC573B5DEB62165CFF8A5F4F8059A478EB" + "F6FED75F1DACDC612C2E271E25A7083E15D33697270FD442D79FFCB25DB135F9" + "8E580DC9CE14F73C3B847931AF821C77718455F595CA15B86386F3FCC5962262" + "5FC916DDB4A08479DCB49FF7444333FA99FBB22F1AEC1876CF1E099F7A4ECA85" + "A325A8623E071EEA9359194EEE712F73076C5EB72AA243D0C0978B934BC8596F" + "8353FD3CA859EEA457C6175E82AE5854CC7B6598A1E980332F56AB1EE1208277" + "4A91A63181B9302306092A864886F70D01091531160414E6335FA7097AB6DE4A" + "1CDB0C678D7A929883FB6430819106092B06010401823711013181831E818000" + "4D006900630072006F0073006F0066007400200045006E00680061006E006300" + "650064002000440053005300200061006E006400200044006900660066006900" + "65002D00480065006C006C006D0061006E002000430072007900700074006F00" + "67007200610070006800690063002000500072006F0076006900640065007230" + "313021300906052B0E03021A0500041466FD3518CEBBD69877BA663C9E8D7092" + "8E8A98F30408DFB5AE610308BCF802020800").HexToByteArray(); public static byte[] s_dsa1024Cert = ( "3082038D3082034AA003020102020900AB740A714AA83C92300B060960864801" + "650304030230818D310B3009060355040613025553311330110603550408130A" + "57617368696E67746F6E3110300E060355040713075265646D6F6E64311E301C" + "060355040A13154D6963726F736F667420436F72706F726174696F6E3120301E" + "060355040B13172E4E4554204672616D65776F726B2028436F72654658293115" + "30130603550403130C313032342D62697420445341301E170D31353131323531" + "34343030335A170D3135313232353134343030335A30818D310B300906035504" + "0613025553311330110603550408130A57617368696E67746F6E3110300E0603" + "55040713075265646D6F6E64311E301C060355040A13154D6963726F736F6674" + "20436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D" + "65776F726B2028436F7265465829311530130603550403130C313032342D6269" + "7420445341308201B73082012C06072A8648CE3804013082011F02818100AEE3" + "309FC7C9DB750D4C3797D333B3B9B234B462868DB6FFBDED790B7FC8DDD574C2" + "BD6F5E749622507AB2C09DF5EAAD84859FC0706A70BB8C9C8BE22B4890EF2325" + "280E3A7F9A3CE341DBABEF6058D063EA6783478FF8B3B7A45E0CA3F7BAC9995D" + "CFDDD56DF168E91349130F719A4E717351FAAD1A77EAC043611DC5CC5A7F0215" + "00D23428A76743EA3B49C62EF0AA17314A85415F0902818100853F830BDAA738" + "465300CFEE02418E6B07965658EAFDA7E338A2EB1531C0E0CA5EF1A12D9DDC7B" + "550A5A205D1FF87F69500A4E4AF5759F3F6E7F0C48C55396B738164D9E35FB50" + "6BD50E090F6A497C70E7E868C61BD4477C1D62922B3DBB40B688DE7C175447E2" + "E826901A109FAD624F1481B276BF63A665D99C87CEE9FD063303818400028180" + "25B8E7078E149BAC352667623620029F5E4A5D4126E336D56F1189F9FF71EA67" + "1B844EBD351514F27B69685DDF716B32F102D60EA520D56F544D19B2F08F5D9B" + "DDA3CBA3A73287E21E559E6A07586194AFAC4F6E721EDCE49DE0029627626D7B" + "D30EEB337311DB4FF62D7608997B6CC32E9C42859820CA7EF399590D5A388C48" + "A330302E302C0603551D110425302387047F0000018710000000000000000000" + "0000000000000182096C6F63616C686F7374300B060960864801650304030203" + "3000302D021500B9316CC7E05C9F79197E0B41F6FD4E3FCEB72A8A0214075505" + "CCAECB18B7EF4C00F9C069FA3BC78014DE").HexToByteArray(); // Password: "Test" internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = ( "308204470201033082040306092A864886F70D010701A08203F4048203F03082" + "03EC3082016D06092A864886F70D010701A082015E0482015A30820156308201" + "52060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" + "0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" + "8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" + "7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" + "6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" + "6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" + "EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666317430" + "1306092A864886F70D0109153106040401000000305D06092B06010401823711" + "0131501E4E004D006900630072006F0073006F0066007400200053006F006600" + "7400770061007200650020004B00650079002000530074006F00720061006700" + "65002000500072006F007600690064006500723082027706092A864886F70D01" + "0706A0820268308202640201003082025D06092A864886F70D010701301C060A" + "2A864886F70D010C0106300E0408175CCB1790C48584020207D080820230E956" + "E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE24B7BB1B0995" + "D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD6CBCA71476F6" + "10C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C6826A4379B65" + "90B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E324C8F884794" + "78705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBFC6C5584BDCD3" + "9C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6EF57D808AEEA" + "AF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9AC8D3F86462AC" + "219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F270F912EAD2E" + "2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D9CFCE2224B61" + "976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED323C416D014F" + "5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5789137A3DE22" + "5F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EAB48BD5DA155F" + "72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCDA642F945C9E7" + "C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F035062BD4E3D9F" + "D896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415EBC997E5A4221" + "349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C265A7DC6BA24CA" + "F2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782563AE8A2A85F" + "64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E03021A0414C8D96C" + "ED140F5CA3CB92BEFCA32C690804576ABF0414B59D4FECA9944D40EEFDE7FB96" + "196D167B0FA511020207D0").HexToByteArray(); internal static readonly byte[] ECDsaP256_DigitalSignature_Cert = ( "308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4DC8300A" + "06082A8648CE3D04030230153113301106035504030C0A454344534120546573" + "74301E170D3135303530313030333730335A170D313630353031303035373033" + "5A30153113301106035504030C0A454344534120546573743059301306072A86" + "48CE3D020106082A8648CE3D030107034200047590F69CA114E92927E034C997" + "B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA32496FDAC8" + "4E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D0F0101" + "FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5CCFB822" + "0CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E19F1AE" + "4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CBDF434F" + "DD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E").HexToByteArray(); internal static readonly byte[] ECDsaP521_DigitalSignature_Pfx_Windows = ( "308205C10201033082057D06092A864886F70D010701A082056E0482056A3082" + "05663082024706092A864886F70D010701A08202380482023430820230308202" + "2C060B2A864886F70D010C0A0102A082013630820132301C060A2A864886F70D" + "010C0103300E04089C795C574944FD6F020207D004820110C7F41C3C3314CCFC" + "8A0CF90698179B7B6F1618C7BE905B09718023C302A98AFCD92C74CEFDBE9568" + "6031510BEB8765918E07007F3C882B49BFBBDEFA4B9414B4A76E011A793DA489" + "F5B21F9129CB81A4718A2690BE65BCBE3714DE62DEF4C792FFA52CCDE59FC48E" + "5ABE03B9A34D342CE5B148FBA66CE699B9F2DDCF0475E31A1EE71543922EF65A" + "3EACB69553ABE4316590D640F6DB58D7B8BF33B57EF2A35445CA6A553BF59B48" + "F4D9A5B7E37AF448DCBFED3A2BD258A4BA3180A66D7508CA2037061517675135" + "DB609B7DF7CB5F39874E66512C57F65DA93E3A43A12929B63FCACC82C5B8D638" + "00713A83B04A6CEB47A3C79D9852AFF5DB58180B6CF8193E7194CF7F0B6EED2E" + "A6697C42AC556C8C3181E2300D06092B06010401823711023100301306092A86" + "4886F70D0109153106040401000000305D06092A864886F70D01091431501E4E" + "00740065002D00650037003900350037003300640030002D0037003000390036" + "002D0034006200300035002D0062003400330038002D00640036003000650032" + "0030006600360030003100300034305D06092B060104018237110131501E4E00" + "4D006900630072006F0073006F0066007400200053006F006600740077006100" + "7200650020004B00650079002000530074006F00720061006700650020005000" + "72006F007600690064006500723082031706092A864886F70D010706A0820308" + "30820304020100308202FD06092A864886F70D010701301C060A2A864886F70D" + "010C0103300E0408812C7B1E5FBB35DF020207D0808202D00AFB0F5D92F40AD4" + "CCABAA4805775198F5988210F0601C39EA4A5B025A0FADB6A95C3ED3CB86E65C" + "B13BA11216244BE2773705202CF5895D9E31E5FC208A9DD2D90B47495475A078" + "B1B531AE496E4E534E4A23D828D2DC3488D982CB05FF9A32E7C60FCADEFA8EAB" + "F01F1D29E0650DAC688F434C4D5D8A26C4D7AD339FD0A2C4E22785E07DEC2FB6" + "7D041FA03BAE4BD6F3175EBB65EE79B276FECE8A8155A925792DA2F8AF2FAAF8" + "75AC2207078643C6E3C3AFEF37FED0AA60BDB06C8C1908ACF8FA2BCD28BCC8D4" + "47D998449108BA7A03E7AE6A439D7310E1A1A7296DBDFF48F7401E259ACE7B0A" + "D7B77B06001B0D526278B109217A7FF14CBA143DBCA99604EB2067D1DE3FA94D" + "D306D0937D9EF825E3B5B425F1F01A2153ECE2DFFF81779B7678626965F586DB" + "B519633EE3CEBD9FB14F5CF88DF6E907176D79CC6A7B9754C5EA02AFB549C65B" + "612866D48D294E44EC8A74CB36592F1C40C4B53640F5AE13F0A7A7AE731942CC" + "5091C57EA07743373404698E347A10BF0433F495B69FE8077EC8971B8B322DA0" + "82746883DE62FF08D3BE6D0575BCDAC392E79CC9B286953AE3B17D27C477B040" + "63AC2BEA6AA74BE63456DA2DE4685E8195EF620F19FDA8943515A4BC2ECBAA2D" + "16DF0237A9C272D6418F948715238EC5CA386E74E4AA67248A56A285F1FD2E17" + "A5F0F09DD3448BA570A056DDC7FA275A42CC0D524911BFA8DB42BFA04588AE5B" + "5044CABD353B9090F9F8CF02514C9AC0F347A9BE2A03EC351BAE2D1AC42CAC2B" + "89C9ABF3600F41EDD4447CDD14192F85094FEFB95DBF260A6739276A279FD104" + "E346A3FD238F7497474B1B4F8B7C02E4EECA34284C19D0AA169C178207BB1F19" + "62CD5E0C8A2C7C55249628F0BFC575DF2ECB25D36E1B29631A612945B9A99070" + "5FF55769B50D0B77725F61FE55284301A604C63BC7FC58F79CDF89F7E57ED060" + "CDD855DF59E9A8C9A06EA0DFECA32DF2A5263D0BF72B9D485519AB87EA963D01" + "9BF9F6B1D77ED4AA303B301F300706052B0E03021A0414AF6FEF9E53E1144A81" + "53A9459AADF886BA2979990414AC82239C24D3BB89B37A6A6109D7B43ABC433D" + "12020207D0").HexToByteArray(); internal static readonly byte[] ECDsaP521_DigitalSignature_Cert = ( "3082024D308201AEA00302010202101549950E8AA087A34C179BE49774C8AF30" + "0A06082A8648CE3D040302301A3118301606035504030C0F4543445341205035" + "32312054657374301E170D3138303930353130333230395A170D313930393035" + "3130353230395A301A3118301606035504030C0F454344534120503532312054" + "65737430819B301006072A8648CE3D020106052B810400230381860004019D99" + "4545E2E70D4CD0901FFBADC7B6CCEED2DC4EE69624B7F0B5C3E81F7A8DEEAFFF" + "BC317A3768D03F1582877D1D84FC69554B76DFFAA439929D94B6BE5CBA8CBA01" + "ECB0CDCD730492414D10A00DCA812CEC46D6D92B9142297500C543652FE54A81" + "427E18EC155EB05D3426A28F24819F5293F3FBC95A9CD7646D5D4D046753ECE0" + "B9A3819230818F300E0603551D0F0101FF040403020388301D0603551D0E0416" + "0414FFA852184A01C69680A052AF5BE279E949718DF6302E060A2B0601040182" + "370A0B0B04204500430044005300410020005000350032003100200054006500" + "730074000000302E060A2B0601040182370A0B0D042045004300440053004100" + "20005000350032003100200054006500730074000000300A06082A8648CE3D04" + "030203818C00308188024201D8EB229D9D73C8C6634E305836E938349672D12D" + "73BFC5A87E2CD2985FF64EE44BB2800214E4839A2DBCEAA3F2342C269D74126A" + "FE248C0C0F7C700B4680CA8F36024200F6625A58C219C389F2B4127BFDC228D8" + "2765E2F9399DB66ED71EDF4D64F85998DE15ED82A75F363E42432BCE108CE55A" + "41A9899160F95848826A9CE39498AEC2EF").HexToByteArray(); internal static readonly byte[] ValidLookingTsaCert_Cer = ( "308204243082020CA003020102020401020304300D06092A864886F70D01010B" + "05003029312730250603550403131E4578706572696D656E74616C2049737375" + "696E6720417574686F72697479301E170D3138303130393137313532355A170D" + "3138303431303137313532355A302C312A30280603550403132156616C69642D" + "4C6F6F6B696E672054696D657374616D7020417574686F726974793082012230" + "0D06092A864886F70D01010105000382010F003082010A0282010100D32985C3" + "0E46ADE50E0D7D984CC072291E723DC4AA12DF9F0212414C5A6E56CBB9F8F977" + "73E50C2F578F432EDADFCA3A6E5D6A0A3ECFE129F98EAA9A25D1AB6895B90475" + "AD569BF8355A1C4E668A48D7EAD73206CCA97D762EB46DA75CF189E2EC97A8DE" + "BA8A4AF9CFAB6D3FD37B6EB8BBED5ADA192655831CFDAA8C72778A314992AB29" + "65F3860B74D96DEB2E425216D927FCF556B241D43AAF5FA47E2BE68592D2F964" + "F5E0DE784D0FAD663C3E61BD4A4CF55B690291B052EC79CEA9B7F128E6B8B40C" + "5BADCDB8E8A2B3A15C7F0BD982A1F0C1A59C8E1A9C6FC91EE9B82794BA9E79A8" + "C89C88BF8261822813E7465B68FFE3008524707FEA6760AD52339FFF02030100" + "01A351304F30090603551D1304023000300B0603551D0F0404030206C0301606" + "03551D250101FF040C300A06082B06010505070308301D0603551D0E04160414" + "EEA15BD77DF9B404445716D15929ACA4C796D104300D06092A864886F70D0101" + "0B0500038202010046AC07652C232ED9DB6704C0DD318D873043771CD34CA966" + "91C04E5B7A311805E965957E721358B2ABA55A0445864251263E09BFE2EAEB64" + "43EA9B20F05502873B50528E48FF5FD26731BEA1B13CA3E3A3E3654E6A829675" + "B9D7944D734C48D36E19B88B77320A5096BF7462E1B4D69F1DC05F76A9417376" + "D5127027B1BA02380684DCEB75A4B14FA36B2606DDBA53697CE7C997C2FF13E4" + "66234CBE07901DF33A037F323FEF8C4229F2B7D030BAC88B4C3D84601576B0DE" + "32F3116C6DF7E9AA29028289E0CCA89F8B809310C37E9BD514536131D9E66AF0" + "6B1F36BAD55C9F9D6D1393CF724D75D3441AD67491AA76C8C31AADE22209831F" + "C079B49408ACC2C0D975EF8BEE3E0F6A01DA4DFC6045433BA6B1C17BB0E3E181" + "22770667CBD6197413569470BF0983BF358C6E09EC926631B0A2385D3BF9D9F3" + "0B5314170865D705CA773652BD66E1B3C112D7DA97CDFB9447FBFCD4DF674AB8" + "A6F430760276B7D8439BE40961D0B7F9F2B7AC1D291C0E67C1789FE038B6652D" + "24FCAF0A49CDB1E61FBA146AEFA3D934BF3B6AE8A5703CCA80AA500B56DF93FA" + "931E2D71E292042342CFB073431AF0AA1ACC0B5F53EBF66CFECD52EB08B11628" + "000F5EA01AB1D8E89F219178DB67B2CD68AFC2C0C248D8A65FD9AE1A0DBFF84F" + "3BBF2077EBFB373F6ED8D6C7CEA7BFDF0425494078F293949496B0BEAF63CAB5" + "62C297590A737174").HexToByteArray(); internal static readonly byte[] ValidLookingTsaCert_Pfx = ( "30820AAE02010330820A6E06092A864886F70D010701A0820A5F04820A5B3082" + "0A573082059006092A864886F70D010701A08205810482057D30820579308205" + "75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" + "010C0103300E040809F1CB8B4255EADD020207D0048204C83EF1251C78FF3815" + "CDB0648F20FF20FA0437E5AAC5CB91C0D547755113724A913C02427A12A878E3" + "B161F388F4DA9AEFBBA5FEB274CEF3A35CC2EC4BFE32442E5B6624888D41FC3B" + "EA02BBEDA034BB196A3FA41E23DCEB6F6E906FD86FED066D547518FD628C66F0" + "1AA4B38F3DDD94D63A5B336B587BAC4D2B739EF096A902ECC4216EC284099F10" + "C93785AFC3939A44C22FD027E4E643B03641FB3B76B21DB632D8522A365A495D" + "5AC74CF7765E294CEC55C73F6A4BB45ABD214D7AECBC3735DA41D8FC66CD5C34" + "54F354E16084D0E1984B20423219C29CAE0FDCD16A16C5BF17DB23DD8F2B1C1B" + "DFC9008B647D2FD84E4EC7952BFDF4EA0F0A13D57CD530109BFBA96DD3F37F01" + "7F7BA246C35A9D5C0A2294A2EEFE35B29542A094F373B6FFECE108D70CEDB99C" + "A7172B17C6C647CD6614D3FAE0C02B3D54062FD8392F152AB1B46D1C270A9F19" + "A48A393CCF22EC3DA958C35A8A6A3E7CFFDC2C54090F844B3B73C3CE7F7EF26C" + "982567ED621FDB93E402FC145E6D7E8D7F2F9C56F870823C98B81586F34C7C96" + "CBAA5A67544964FA1BD70B9C5E8284ACF22FFC69BF62E389C5678E44CB10D6C3" + "D3F73DA7BF12B44D74C0233C140ECC93C5F0118C8F0D9B6FFDFB23966ADC070C" + "8DBFAFE78AE1E05F8FA7C75A22FBF7A8458B9C61B1F2BF2AD2F0A6C6D15AAD55" + "D960F173AC3D9890CAF50228796FAD6C7EAB1C8A3C8E9E42E4A4DA99C4A67FB3" + "E2AC958AD989508538C96697A0CFBEEB38E9CF27DAE3AB9492729A205CB25340" + "85CA0D580DCD49E88DA7950F99CD05523885B5257BD302E1B449F03941BD0DA1" + "ECCAE6A22BC9F7E446F7F6FD4EE850CA3BDD7338F705D93C2F196712250BCB1D" + "A18C9661E195486768515BC2761A66F61770589A62D172DF8EC288549E86E518" + "7B04E1550154FF45060945BDA07014F14EB554A5A324F9B79DA192F79AB0745D" + "F30355DF580778773F2FFC76FB7B367EDBE173AC7F70698766DE6BB384A5C88B" + "66B163E8ABBF0AA44C4ED0D3D51D167E8BEFB2E71D36043ADB098BF2DADD409C" + "1F53F5546D1C8A1DC5E7BE566D14C494460161BFA7CB7E936790A81A45763004" + "689FA9BC33F31B4E86A152700D35B20380F87F4304D7850CA7BF583724328E0A" + "0D9B611B919975DF118B334D9DD96A46A21B00FC3B7FCCAFEA968FF030EA5D8F" + "9AD8624F668B2A7E433E54547EB89FB876A7E1AD2E9DAA38F30E938D8BCFB431" + "6E12FB8BEBF57FD0BF542E55386A6DEE074CFC6A33A55A57503CAB7F115DB875" + "C8EBF787670BE98DC03C65F2502D6F8D001ECC819BBB9C60BFC3A88DB8A117D9" + "9E09C13AC23324E15E5EE3C22B084D428FF2DFB37F917F7629F8A15093BB7777" + "B1AD8CACB4A5C6271E8B21A18DB95D6196E9EBD870521CA16930F2D1D43962AB" + "B8413016DA0117E10AB2622FC601DD08826429D8B8AE9BC6F15AE78392C36BC3" + "06FC19C90AD43BADD9AACDFA8CC16075529BFC8C34766C12783BF2F2E0B393CD" + "4F8F05D588B99218806D57CD5935E25DB2AE20DC4CDFD7F5111AF9A9EFE45349" + "42CAAA72F1F95636085FEC84BB98D209FD4222BC5F84DE5926A28FF7A5B7548A" + "B4FC3331431964454A0C532C205CF8D3872C561E83D805F7BD7DC811A0A90C9A" + "CB308E8F06AB739DCE97A840B4AFC0E884982CFC9B37897CF272ED1F46027101" + "BC97B11F04D64B07556DCFD5F609C5C9FB4B3F2AB345CAB46211EF0BE5ADD6BD" + "3174301306092A864886F70D0109153106040401000000305D06092B06010401" + "8237110131501E4E004D006900630072006F0073006F0066007400200053006F" + "0066007400770061007200650020004B00650079002000530074006F00720061" + "00670065002000500072006F00760069006400650072308204BF06092A864886" + "F70D010706A08204B0308204AC020100308204A506092A864886F70D01070130" + "1C060A2A864886F70D010C0106300E0408C10D9837801E56F8020207D0808204" + "78827979D15533A4A7210A435D0189C133B65B00407E85BC44368D066C65007C" + "256EE51A55E35BF8EE7C6FAC3D67FF7CF2031FECDCC356A51396B2977E044A79" + "E6C6CB8859E4AD49765468A4A467071292EFE47AEB39856FF8F00B5C6C6190EA" + "B20CC9A7C630C09E3F351ECB20CEC1BFE7BEB5A3FD534BAF8CDB658318A37279" + "269A11E8A87074FF0B111E2CFC493BD08D7887A7A222743B0C50E47F676F9B47" + "449F8FCBC6AE5F5A3456AE6BC3CB8A3CF28C59D0A16FE4336E0BFCA0AD74F95E" + "0F1010C3F698E16418E46B0059AB8F3DFD31FDB99132665CEC4CDAE8B6C1D0EA" + "9DADB8E591769261C27188CD5FF8D5C56E6866D85E1502254823940EC77096F0" + "6D3A261F49495AA60114BDDCA27C603F78314678CB08738FA2974DE03BE315F9" + "1FCA511446C68127211CF575948550DE4F7FDBF4AC31E395E12EBFD4BB99F470" + "498846940A92B6F85CF5D745B5230EAF994DD368FF55809F299213749CBABE54" + "C54D39B2165370DA43468409E73C55EF784D17496AAF8B6B5CC0F9FF234D7CF5" + "C84C248E91F8B08F74A8A953F60407940A2EB9576655CD9946D468DD6B3DB634" + "A30D4FE8E09C51AAB99C3DB5CC834A447EFBFDACEC9A49AFD675BCB247575B27" + "ADEEA9C5A6F2FCFF71A57EA99B467029C3E40D94D2849527FB90B9BF39294CC1" + "AD1F4CC18F75302FF241E05896A357BAAB88BDA8F7EB22B9AEFC5D7600154631" + "3C2E87452F99997CF4747CA936BD9199C61CEE5E61BBDB80C17978938F241D53" + "AAC97758FD1A77F3C7C28F88F1BDC7E74176CA41B73B7042A6C3C7AE918635E1" + "1EF4F2607588B0FF7C656541C32A1450AC71AEA42C14E94F0408A09902C30D10" + "ABE8396EDF5760991C2E02949EED06D091A2AB64827A53F29FA8B8B79036DA26" + "210A7C34EBE73590DAE990666E0F0F011EE8E41D08E16B28D49F30D8539EF18B" + "61860EE73D9AF98E4D3F17A50D06FC0592C218F38C33E0B526761D030E037B27" + "348CFDBB72C6B635BAEA497BA12618BFA47A9E358EE834FBA8A5FA9D30A66CFE" + "BFAF1E25FAA361F94433B40628E7423491BBA29116EA6ADDC6DFEFFA3AC2AD83" + "83C3EA05DE72B7CE357612A9C60CADCD42DECCD40438A9FC8E5D9413825178A1" + "9D67E7B13449F118A6B56A4F8A5DCC0AA05D0AB40B8FE0820A2399307331524D" + "B3389C97181EDC2ED2C5B72C1318B406CF99120CD784B85238488D1DA062478D" + "1EE6380F9954BE5442C1C00ABF8D284AF95937E2D515E2E8858F3C50516CA00F" + "E3F632BB05EE4AD63A6F2D72C7F2B06DC993866F6A740C1EF5159117437F646C" + "A47AA4BE5936C2F6BEF4C628A744FA2A2E2068752FF43BB9CB29C986D3A466FB" + "F3A107E8D610B8236E4E074CD6B32B50BF1C389CBDC2A92FDD19047450E04B4F" + "B963CA94860C1DF05D9FE1D202227E351BC2226572D6950D7E5242BE17DCC992" + "A989B7D13BAB9C8EC76FF5B8DED7696BBDAC058F6183F6F799365EA1DCC4F1B2" + "43A35027BA2F02E19DFCABEB564536EDA7B073519C60294C4AC25956D9F9DA60" + "3C5E4F335D7570299993460BDC5F20776F22D745A6B3F7E80EC69DA881AC72A4" + "D6B7AADF7EF19C77A2555C1CF8CE1CEB030EBF1C365D40C9C33037301F300706" + "052B0E03021A0414AACBB391FF9626295715807ED7DDEE57F716A5710414658C" + "344F4B20292DD9282953DAA4CB587AD48714").HexToByteArray(); internal static readonly byte[] TwoEkuTsaCert = ( "3082044030820228A003020102020401020304300D06092A864886F70D01010B" + "05003029312730250603550403131E4578706572696D656E74616C2049737375" + "696E6720417574686F72697479301E170D3138303131303137313931325A170D" + "3138303431313137313931325A3026312430220603550403131B54776F20454B" + "552054696D657374616D7020417574686F7269747930820122300D06092A8648" + "86F70D01010105000382010F003082010A0282010100C456AE596BB94EA55CE7" + "D51785F44223F940237C1F0A279533875427547BDC3944B73E8E6F4463800571" + "226147CEA3649972F96F128B673BCA6BBFD70B5178FE93D4DD7BE9E4D450AA0B" + "4D177F24DBCB2A7A13D7F10BABCE0E9AD3B853F01872196F6905F523E260555C" + "AFC5B158A82ED52D62BDA32142982EE8BB4E011E44622B59387B8A287F4DD7A1" + "5C783EAB5D4736CAB0E06A78EE50A7BA59DFE2C35DAEA0637FD581DB485ACA9A" + "57B94585A9E7D7BFAEE31F92F96DB5F95DDCE52B839BC06C30191014FE6804F0" + "CF4CA29412EB34D87303CE5FB49EC3E4B1A7CB001B6F117E1D5846A605ECF5D6" + "8FDC32EA972CC8521B823708518BBE59D15D10DB79990203010001A373307130" + "090603551D1304023000300B0603551D0F0404030206C030160603551D250101" + "FF040C300A06082B0601050507030830200603551D250101FF0416301406082B" + "0601050507030106082B06010505070302301D0603551D0E04160414B163E5F7" + "BBB872522615BB55850DF3D636E8EA6A300D06092A864886F70D01010B050003" + "820201008E5927A04E7D6361819B565EC9C3BFB59F1BBB57007B4534FC5B2F53" + "6A02BAFB2EC19DD8EE65DC77F34E2E7A4A2EA1597EE2019CFEBE8BA45BD35A53" + "D201465818F1B6E0E891FB380813E27FC1F6D9F3D5DC4C23267FB4326960E7C4" + "D69CF837904E694F4DBBD1AA346FC058B158AAC7EDD7F947F67DD09D9183B84E" + "B91CDE170895B830F4DE87850BC79C3E27534298BD8C7E7DAF3CC1242777435B" + "2A80CBD57C015B1B52A5B46D85187E5FF20EE68A96FB705FAFF4E335EF4FDBFF" + "CC5D981943127CE41EFA8C1D7E2E05D03D772E0C02F4443AB3420B6E3D1607BD" + "B2416268AB7D9D2B5824AD82B06ECB58B41C0AE092D704F77023F6CC8918F7D4" + "3128357B7504276C805E6C27A0A5872C89375F69FF14E91B4A11922DFE7B8142" + "8B103B55973214426A063DE2955AAB165CDF105E574F23C00E50FF5B8AB86222" + "460734EF5003A0D780DA6FEE9B8CEF0AF45C0BB1D0D142C4A2FDB2BD9776B049" + "B70FB4B52D2EF2141E3C3EC8F4BD914209C2F2EB31FAB2311F906EB48D4396D8" + "5C5D9B54FDCF52C00FEDB9F399607C1D95BEC1D81BBF8B9E35C36BC72FD90834" + "AE8D4A02DFF4FD65DB9748DB626FD4D387A4E0E5ECB73168AF3BB3C788DFAD4D" + "CECCE43F9513EA99F1AFFB2B900F5AC55DE8D7AF96B243BA663500A63E4A35D4" + "7257229376EE8C0179396C355DFEEEC03F8773BA1DD5B0807E44EA1E11257751" + "67020DF9").HexToByteArray(); internal static readonly byte[] TwoEkuTsaPfx = ( "30820AC602010330820A8606092A864886F70D010701A0820A7704820A733082" + "0A6F3082059006092A864886F70D010701A08205810482057D30820579308205" + "75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" + "010C0103300E0408C4A9C5FF5EE508D5020207D0048204C8344C1DBD71C360A0" + "B4ECAD9F7F43F25272B5C99F1D54A7A0926401082B4E1512610D52B15CBD8203" + "36AB72F4E57D083B49BBD606F5C1A268B66E7931E0980A06D8EDF5B5C0BCDA51" + "908E21890B24054867912D65125BA0F75B561175A053D2F875C1C846CDC6AFD1" + "7599AE877B8CF18585BC405B1E356FD49AAB207BC7C2BBCEF1B0E9FA2EBE205F" + "E5F98F825BD9564FA45A7FF011EA41A247AAFA06391C62BAC548A004A139F9C8" + "8039B1837066BBF5DD7E8DCEDA3B13ACA5214A53C8D6D748B4DA885CA59741B2" + "5799051D59AECE8F06EE0C637406A91070C7DE72B2FAF982BB0A9D937C517D5D" + "B0F4D0EB69FDB597F8695A9BC42DD5F87F56119AB5F3E051B0E03E4A069FBF39" + "3C5592E1BC28264BDED3ACD7D0CBB5DEE9B426101C6CC5752A5068DF4520C71C" + "F10875F1F23BF84D4B6D3A2E133E059A8B1F02B47258F36F84AF4EAC85045489" + "971E63970A614CB05C3FA28A711F8DA220C23E463E50B17408E05316F1CB32CA" + "37A0C4262081E9C60D897559FF167F2F9B58162399368DD5B85309E9B941FE32" + "356258D2EBBBBAB957F496742DB2CF7D8233EBF879887B3F07156BFF9D2CF87B" + "D495C684CDF46E451715D4CA1DA21F960868BA70CE88D4D8904EDB97EF69435B" + "DC89648A1C330757D51B9D94AF48814109B13EC4AAE6EA99B2ECE5DFDD384F71" + "E3A4D39328F5FC55344E2B6EC68D164F57B92AC17D6BF52AF153D431E06770DF" + "53A8F14AC579E5E130FC5C3A665E5BEE8CCACC5188191B00EFD13A3A0DD1CBA2" + "FAB565CCE5459DCE7CBF8332A3FA1A6E943AB05A2BD28A35025A19DDE18A63E9" + "123BBA96B0147221E7CD90CA3A8DFAD634CF8A24EC1AF619CA7B43D844B078CA" + "AC708A4D1775AE368B583785307CA3F73C370740DAE2163AADC966BED8EF2648" + "28557C1F10BFFED48ACA7ACBB60CA16724F0FD9A2C79B4556A71C7BEAE5549B2" + "BDF5B165760DF0C7A0977D923952C9DDC95D89D379E0DF0E292D1534753938DC" + "8764451A231F132FE3F40C472CDFED28564002A39ACD4B7059CC284E72D27ED6" + "4204DCE2CF30FFF82EE788950CF24358214406CABAB32332CCD7D14A141162BF" + "832B1091EEA2C845DE9338D96917065E0CBEFFD292232B20956DFE8116C724F8" + "EDB03BED1474460B0C3C45A894C7CEAEA083C2FD5162C926F5DD945BA3BF3A53" + "45E82A93F8BCF462AF4C51F4784F8618FC2DB64B4E4A497F0654F573A2F83426" + "DFF119440981C9ECBDBA7BDD2AB18F2D62B5EDEA6E2396537EEF3A4264EEC3DA" + "4843FF0CD344204C8FDF9C92AF1278937694B30EBE6238AC70D19719D43D77C7" + "6B117C4048A7698B822BF371EEC55C1A4C51A13E4A84822F5370616A67B25723" + "0BB9B14443A8FAA13414244CFA353E414C9E652C447BE58AEEF982FE4A12FB64" + "5FCE47038C15499277FD0EA308036497437DDDF39F596D48FAAC1177112E0929" + "234E3F5389DDC21CE14362729AF3EDCD7F2641A8633C13C1E10FBB808E5881D9" + "A19778C52E8A8D9DD97766B18EAA9F147AB7B184D7DA131148A70FA0D2FB079F" + "E4E4062211D0EF4C3E40D49025BC84C68FC2CAD10F2F5AF80D8174B2A05301D7" + "35F3688D854D5D9A2A4646D7F4FD49A16F9432197EB581FB71906AF7D2A0115F" + "418AA18C1F14285C7197F3508D374947A8769A91711B0D159A71CA3258529DA0" + "C918D8E53E0ADA32E8F32AF11552ED557DC1D8F0F1D027669221C00529B44031" + "3174301306092A864886F70D0109153106040401000000305D06092B06010401" + "8237110131501E4E004D006900630072006F0073006F0066007400200053006F" + "0066007400770061007200650020004B00650079002000530074006F00720061" + "00670065002000500072006F00760069006400650072308204D706092A864886" + "F70D010706A08204C8308204C4020100308204BD06092A864886F70D01070130" + "1C060A2A864886F70D010C0106300E0408E42BF45F0D448170020207D0808204" + "90BE13F1716CAB0C61D6269860EF56B1C6695C35AA4B8333CB772579033EC447" + "9B83662C6EF04487BD6BD3EFC7BEE8C17F5EAD6E73389A9EFD73FEE959F4FF68" + "D31616FA6D24D918F0377555CD68AFFF60F7E7AAF1619C2E1F4B057F5D2CC20E" + "DEA3A8683DF2DF5E6D3C062065B38FFC4C16E7AD27BD31742C8732D09114B768" + "FFAE7BEFD13303C64E8CA18F2571BBB1FFCC3A28BDBDE510D841FF781D7C615B" + "178252E13D24B89D0DE8E47D9160CAE6BDF5E3959BA35218EDC43708F68CB2E6" + "B37BFE52D05141B5BBD351C570B18848C68AC15E109467E373904F3AFDA06905" + "0C1596D2ACED9D2733EB1FA0CD503B06828944463C579986BBC24B443261F1C2" + "2C170F13F3EEAA0FF2EF63200612723AB4A0C768B03C6AC3C6B8D967DA306018" + "2D2E3B412EE8E6E0639C282ADEC3899F36D740CF1CEA888824FBCCE2A7A22AF2" + "06681597D80B907F50F7044B928BFAFC10F2580B5F7380E2C43BD6F273CD7EC6" + "36F3F4F3AD5F2DF9F48CF4B0A4EBB8CB3BA1DDE3448C5ADE45C75CB80CCD61A6" + "AFB2E29BA3833A6465C34ACEB7E47CAEDFC1A6B5DB7E3DE594026B648082732C" + "1A3804E882DECC2018BCC27A29AAB4B98873099025449B9709EB9C0B5F84EA34" + "4A7CE3D0829DE1ED1C89B165A1130DDC8333E54486A94E35A8C017B21DC38D74" + "C6C0A685D68103743DD7DFEBBDF0D9BC55DE11DB3F38F762415BA58B2E52CCBC" + "72B76D70EA1BA331B24F3817DC635FF59A1247A8F6EB1AAAA257388709BE7E44" + "E8A3716A4A2FA0D57E07853EBE9BCE05FDDD23215531BFBAE5E304A9DE44DA93" + "6AFF963085CE099665B03357C295D33A338EDFE664EEF200A957484D51736FBA" + "73924014152949BDF128248ACEF561F51F08456E03E3533354283A74D0BDA10F" + "53BEBD5710C0735C2960188781EBE4B9AC0E658723CBD09C8898FFAE79E5D066" + "EBE4586777E1039D38EFF6C74ACB80365341A868C610377C03DE1B691300FC4B" + "76A7192FD2D37864CFB336852EE9C2FA8AB96F196A0EDD84876B3278C4200143" + "11C933D8C759945E3565C80CE8E7782C4BEC074FA87EF25D951D846FC160A0E8" + "ADE67650FAC6B2A7C8F9798CBF8DAD6B23CE7A429995051CFE6941EF7258A10E" + "2BD776B6C7DD59823A50BB767E38D6CA099553AD0E3982296DBA8AE6D72CC473" + "9F4A9476B113FB06DE80B32F65FEFE0545CB44A3F5940C6776806168C534BC18" + "4E73AB8F7B0E855849ABBAFA9D832246329794682331A05DA97848262E9FBCD3" + "0A4894B6EEDF42150B23EADB3362C54CEC2CDFA9F36F67AD22389B3487CEDB98" + "174644FC2A7C5FEA11488F031AAA30A9F7FE15662C86A0AC5EBAF2FB47CF555D" + "B8D1C85410107C2CF40099DA3B281F0DF391E5602B64DA73B585895DCC465338" + "29BC0E72F178F41179238049BED59D0602BCAD8AC9E9BC140306D8BDD4150C6C" + "4DFD8EA353271B928EA23482E719A58D02515EA83DB54252CB8D466EAC9FD1EE" + "71D00DC6D39362883364E31CBC963CD295CDB490074F5C43759D7DD655AA8A46" + "EE5FE06E186AB3025E71AAABA9DFD8A105ED86B85FF7C772F596BEEE31CA5BF2" + "26BAC1F59123893945BB052A48E9BE2254FF1512B1C2E46D34111F7BA35EA906" + "74FBC63FC70A18F095C2AA6CD060A7B52A3037301F300706052B0E03021A0414" + "A519F103F114AFAD5EB7F368DB4D0748559CDD190414584DD2F41EC2DBDAEA69" + "FB2FF401BD9FC3B57572").HexToByteArray(); internal static readonly byte[] NonCriticalTsaEkuCert = ( "308204243082020CA003020102020401020304300D06092A864886F70D01010B" + "05003029312730250603550403131E4578706572696D656E74616C2049737375" + "696E6720417574686F72697479301E170D3138303131303137323532335A170D" + "3138303431313137323532335A302F312D302B060355040313244E6F6E2D4372" + "69746963616C20454B552054696D657374616D7020417574686F726974793082" + "0122300D06092A864886F70D01010105000382010F003082010A0282010100B1" + "74BCC25C16B5B726821C2AD59F0EDB594832A15FE186A087FF40A8BC9396C55B" + "C0DB2B3CE3EC5EF26A11AA87073348435417982D29C439FA3EC94A62B4BCC9EB" + "CE0236B7E5306B3144E71373B05C24D3C1EE7A4D263BF11FC54D09E4B674F593" + "389AAD503930EB7CEFECCA3A64FCCCC15E32E4B304BDAA36267E6BF2DA9584A7" + "66E1862758D04E7FF9CC5C46CB074DFBCFAFDC355BF848337CD38331FE8556B9" + "F350C6780C7260F73FBCA77FC454247B018E937D2002C9590E07804233EBC28E" + "7BC712ACCF6A125EA60B86A87217B23A91866BEAAAE842D0D0D02E87F5F123AB" + "811EDCAD7A6819E88B0F0D0932D0748EE02726D7138B1ACEB7A6D4090245DD02" + "03010001A34E304C30090603551D1304023000300B0603551D0F0404030206C0" + "30130603551D25040C300A06082B06010505070308301D0603551D0E04160414" + "610479D21BFEAEC87835A7D03714613D566F25D3300D06092A864886F70D0101" + "0B050003820201006511E16CB557E9936363DF92EA22776DD9AD1ED6ECBFE1A6" + "B9B718BAF9828AD2B8CE5450F56E1371B54577DE1146FE82089A4331D063DA8B" + "3CE786945ABBE4D11F4465068B1C3E4CF987C2C014BAD8BCECCC946EF3C5C56B" + "0DDECFB11967A10949A6D111DC96C627D2F1D7969CA6BA7AB131367E89D950C5" + "0B756E516CD4CC6BE679BB53684517236846DCE33BB49235CB1601A6657CC154" + "8C2D57E5554B2755FD047922B0FAC86437758AB72C1A6EC458DB08D93CFB31D4" + "8C723494978D7F32B940E5519852F9B6EA4F0363B59FCA7F8A6CCDE595896B91" + "869C1D90FF2CA0CD29F9AA5FF452470B752052BFFBE2CBBE00C68F2DDCBE8C68" + "53136118CFD1916D711BF90021C04FB5879BE0974228F79C71532FB2B5DDA1E1" + "E89BD5EC9015F2207F7C55D72E976A87479AB62A46465E8D75466492F82CA574" + "D788B27A5CA251C9BE3A4EB90F6E7F238CE8AAF46E598DDD70094E148DAE4DAA" + "21275F79095ABCE8A47CC362386FDE498D102CCD42B2313AC88FC11E21DF8283" + "631329E61F35E8DB12EA8D33DD02B8987C7FC38242412EC97CD52A7A913C6992" + "D87E71A75F9654F7F9EDEB80B0BBEA25C5A22CCAF388D109DB0EA7C79247CE4D" + "C89F390EB8C6CCC19FA9EB5DFC5BFA4457DB30B27CA73EE1C19934C8BED63E58" + "F227222B86010D9521324BDDE04F47BF5190778C6B812ED78AC7DD8C82FBD0C4" + "0DA1EE040184500D").HexToByteArray(); internal static readonly byte[] NonCriticalTsaEkuPfx = ( "30820AAE02010330820A6E06092A864886F70D010701A0820A5F04820A5B3082" + "0A573082059006092A864886F70D010701A08205810482057D30820579308205" + "75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" + "010C0103300E040830D97AD5E5020804020207D0048204C857D388EF52DCE112" + "B6D73E8611F6971BA662ECBA8F80435F83126D213190D6F77369E8D1213CF1C1" + "7791AC985C7A0125D1D4728B841FE7BE3E9C44469CBE672377CD97821B49BBA2" + "75789D64B648F4F243136E9448166EA366EBBB973041C437E1BA70B609761F03" + "03A5ED03C041732D34F070555B006FACA2B8639A0B609D1A7F8A88ABD260CB69" + "3365D9181A638A6ADF69385C96BC094E6EEA507160F18A22E0552183C586A45E" + "C680CE10B56E1D3956F704C89A0981429C470DB378DE1CF21BD67E9EEB43B37F" + "E00117CD3CDB02398FD0D7FD4B48EA38CBF6B19254E957AD2D8A0A4C3AE72355" + "590407AC9FE2622C8AF04BF17E62CBB213F9D29999BF184532BC64E2ED1A5323" + "1501741A1352F492AFE713503A950DF12E9BB505EBE9C80DF4DB6CC9E1EE0CF0" + "02C9CB145E265F7D84A448B9C7462CE25EEBDC9AB3A6E1C996FC535FF7627163" + "1CA7E36C1614A9113C96EDD951F2B3B7508DEC6A2BE6889436A741CD170B6201" + "D546430CC38CE1E874D78A9D6E4D9665CE8261368FBA08C7456E5B01723D3465" + "7AD715328341B4BAD14825D1DB1B0030819B61607E2F4FE76D0EF1616E2C1F96" + "4395FFAAA4A9F7E833A1527B630D862DFF5C8DD6EE6557F55B429C9088020D10" + "309070D8BD46B1512C0D6B68C8C00EBF215C5DC3DE0BD8B4A92E4C3115687194" + "D7DEF524FEA4B02389388C7021BD85EDF13BE19086D08AC682EB8B37F1AC6445" + "67CF6213363D889536CD8A4287A9DC16DD5497A8D06A489D6AB12E4943784EDB" + "559FC02C7DC1E190A9FBCB8EF7D83AEDB31AE1BA8F356742E539E4A7B9D0A516" + "90FCF505BFD5DA6AC8DD67439C2CE9E8D3DFB78A88581BDF0EBB89B810FA7894" + "78D5A5BA44BF287BC8D98DF1B286F2B9109430524DFD5739405E46C755F9C943" + "03C95FF6E89400D1E1D1E814D795FF0B77ECC84AABFF6A8D3C665770778CE9C9" + "A9189DA1E257988AF6588A596F5534D91FA4505581DBB0F8588F97CC3177788D" + "131A2F03972DA2753DCEE18965E032A5326CF50378D7D98233A913387315C71E" + "3FB2D81A78B537BBBD4408C2E8DA4EFE975EFAA785BDEBA40C5CFF9E25CA07A0" + "77DFD9744FE20F783A38A274CDB85A374D1E7723473106DEA578B14C766FEEE8" + "6446C61AAFCED190892AE44C8BDC72D5178C3AB1BE9600CA15F5D3383A6219D0" + "675F2DBA9AED44BF8702777EA6902344AA572535217EF44BEE37C6E507FEB4FA" + "62EF557119608466CD1339C242AFB4F8E0E9EB403E41872B3C5A34B94EF2EBC7" + "91111687C764E4E20A25EF07DAE9E402FB08B79EDB4F5B5C3ADAB14E3CA9004E" + "FEDECD8DA9D4791BA96F6D6493B301698F2202DB9834B423ACFE71324716FDEF" + "6D70FEBC98503E914593A1F511BCD0C39425DAA9981B6BEFA122F8812564D14F" + "B6383F3CB8C2C41449E9B58B3D4EE27651C5B20CEBE786312878E641C20531B2" + "909BE5727E4C4C01FDEFBC635292A663B53A8EAB29A1FA4CEFF11A02AD511AA7" + "F2FD338A86E1876B568074F50B33835186C71C3854945AF082B4DBBD6865581A" + "139B3973A3FD5E62AD88C51D636D616AB18EA808BE982C7C51B20FA239D07014" + "CEE766F9CDF5D592B1D31881AA5939C670A7CCB48D234268D61031A27D99728A" + "4701EF7A241C45A26799C45A8A0A02EA054215973B6F156520544DBE0C3A89DF" + "7BBEEB7AB754495781A4A37F4CDD64B1A3A535826B00E1A710AD4D4A56C17662" + "3174301306092A864886F70D0109153106040401000000305D06092B06010401" + "8237110131501E4E004D006900630072006F0073006F0066007400200053006F" + "0066007400770061007200650020004B00650079002000530074006F00720061" + "00670065002000500072006F00760069006400650072308204BF06092A864886" + "F70D010706A08204B0308204AC020100308204A506092A864886F70D01070130" + "1C060A2A864886F70D010C0106300E0408DBF6A30F31A06E2B020207D0808204" + "783C0D88298EEF3EDDB8C04416DD28F2DA6654714BD9092529FE1181153A60FC" + "552B4D62B0C1F53C6F6337A7C774DBE4396690431E55A963AA509A2351104B91" + "E74B9250AA58812954181B1ED602D9699105960C7B82E91362946292E65C99D5" + "80DCD3B00FCC0FF4B25095AAF4B5E67886B817556D8B69B3016DE071E31F2B86" + "3612A6050FB7D97C5454CE63B842B02FBA72D102DFAFEB01192CCF33BDDEAFB3" + "950C53E1452B449950CA860BEF314B32AFABF6B9F2BB1CAFD064960C073239A3" + "EEC38BA9B30BDF0A9DBA3FCA6F22F47DC8F593BB7102FE0D8039AE5B2317C9E0" + "2DB059C99F06708809362C1676D14D7E5F3DB30E0090697366DDC9900A218E7F" + "99851838A111B9C9C9DD9A696DD096DDAA23175164034407463AFA4664BD5E70" + "3B6AFD659D6C7CD266ABE731F51F96A2D148B919B83888E4416759169C304A15" + "57251FCAE553B5A177DBB5366B031B59149CCE263601A0231544CFD7107BDDFC" + "4037AC0AD99F93D001C4CBC4DBCEDE235875C20789BBE8BEDFDE63D1959C25AA" + "1E410AB081F03CF5562D814C54A9B66A27E74DC261D4E41513927BADA1E993D5" + "20EA81D592B1D4ACEA2577929229B60A8B0AA7499037F3F7F24C1E8E980A06BB" + "6B953090844FE068B611DC4C880A4B2FE21F82002C4305A9AE27C1B17607D59C" + "89589F122721FFB6DC2D95EFB7D96625EE3C6C252E0E3FF25D4407549358F995" + "D9911E9021303FB711B71D7D5F61D6BA845A456B9A832926A098E0EDCA081E53" + "9FABBE54C09DF90D37D349FAA3A9259432491307C216E8D3C160E1D5E994161F" + "BB29C9BBD789CCEB23591B983D35CE3001D7D4A313A9D66356D5B3BC0BB061D6" + "49DFC15CAF2B8B70D3FCF40B1D412E60FFAD5FB4A0F2944F019CD2CD26108345" + "20771F437BF27A586AB0866BF1F5920C488648D463A2C430E217CFB080E91930" + "05589A9670FA9C75050E45100A553E9A21FE300DE621B12CCA03FE189CE65367" + "B1CC452426AD21C67925894905CD594E85C354F85748994C34AAE7E281DC3C71" + "81BEE53119708F6C2D29B2CA987F5620650BE2EA087FAF976BB58349E8B67F67" + "FAAE11559752C31EB34A72FD4BB23B363255530F92E8C0C82FB7ACD6FF4DD7CB" + "AFB831E624522FBDD47A8191957BAF0E9998AB61C5F839B6DFF3A568132A1A21" + "643A576D3562EF72294B13E6662ECF9CBFEC602C7AAC5E01D43759917D95BF3D" + "D572A45B2CAA118965764470C163FACA61D06693273D869214816431963087DE" + "B10FE0316352440E87189532D950E0A9AE5ABE9926907E52F1E4F135B467F4E2" + "8BA57B9F371FC934409526E261926E484B465ED10CFDB25A2F3E6838F41C37F7" + "DF6A88E7063EBAEB6C426B0A4C7842C58CA49581F14337FDF43FC22DAF79900D" + "306E34ED9DACBD6072DF4F34588F28F0F4AE13B431D9F47ACCD6EFB1C4EBBDED" + "D507512B820FB02713948D45F3C595330B271308F0E6DAB862BB917EE9E2B1F4" + "17CE21A26CC17358C11E2BCC514EB241D0767B4971E9B89F94731843B508C20A" + "54345F58E99D430065326FFEA3E1FAC40E24BFB17A51A884CA022944A27436DF" + "8F2C4E296A728496C38076FD3F14B007FEFF015EB42329F7453037301F300706" + "052B0E03021A0414A0E907FF695A237FAB54BBB94CBCE689EE0B4552041426E2" + "132250203B3235FD5023D999B747478D8873").HexToByteArray(); internal static readonly byte[] TlsClientServerEkuCert = ( "3082043130820219A003020102020401020304300D06092A864886F70D01010B" + "05003029312730250603550403131E4578706572696D656E74616C2049737375" + "696E6720417574686F72697479301E170D3138303131303137333331375A170D" + "3138303431313137333331375A302F312D302B060355040313244E6F6E2D4372" + "69746963616C20454B552054696D657374616D7020417574686F726974793082" + "0122300D06092A864886F70D01010105000382010F003082010A0282010100B3" + "CBCBEA8EFAAAEDF982CD046188D2F57FE9FE4F4FEA94ADFB7DE47AE731636624" + "3C4E5F8C2821BF0B01A32048E8A275FD9B3073E0DA2E8870FD9671BFA600A47C" + "8588AAE88150448E6B4C594C5EA288119BE9A3EA369F66EED7C499738B8EAF84" + "5E6B36BCEDF7887D061BC86F12D40982199C1C41CCF5440AEF592A482931B541" + "1B0E0400FB24AF838BA89A3E1393C24B80B4C67AB923DE68B0B8A2218DA93C2C" + "A4908E3B906BF3431839CA6D3FC2A4FC33C4CB58BDEF8982A39DD186D0BB88E8" + "E68819C4A7DA4D29F48F1C1F00098DF41C140FA649204564A3AAB9D0E7486252" + "77F40B9739ED07D385BF9C0F78528CC5DED08A84B6D392874B2A4EB98B3A5102" + "03010001A35B305930090603551D1304023000300B0603551D0F0404030206C0" + "30200603551D250101FF0416301406082B0601050507030106082B0601050507" + "0302301D0603551D0E04160414743B8DC143DEC364FA69992CB3306A9EDEACEA" + "1C300D06092A864886F70D01010B050003820201003A48278ED517B381CA420A" + "E3C12C31C22F49D1DC35EA60B018BCB88C6C3E0FF1E7A301E525B5592649B496" + "7BA62D89AC748DB026CBD73C9333AAE89C5F5D76FC77E970F214F1508CBFBD9B" + "09CD50EF93D61559004027E80BCE6809F196633C22A13CA2CD7596ADE5B4A23E" + "BB4E03367892433357636316F0D235D3DACFEB99631CB437DEB04E4A074B1CBA" + "6C6D722210B058285A3E124EC8148E31B3DE37DCBAECF560076FC0E50965D482" + "DCBF529127CBE2440BA746DC71765516D480E68805C7668A0B538BC489DA2FE5" + "E158BB6786A626BF0AAB74AF042347785B54323CC019CA84347BFF57C025791D" + "69C558A605D46C50297DE1E9576972053A3DDFE5EC8FD2DE0D48B80252C39EE5" + "4410AD46D8128A453758DA442CC2879290A50232B13920D9C6800D8773C2FD82" + "D11755C336CD6416FFE26F97599A29E5D18227949DD4385C74D29547D6C70ECB" + "CBE006AE2D18BCB8708C50E7C46D442A8DEDECEEDCDEAEC47042957B1D18D410" + "96350438DCD8223B17E5FDC3C9C0D9BD47D191E6142A601930817E30F8E0509F" + "D5F5FE269683494F08C55B9ECE6E3D503C81A81F40CC959B858E52BA086D95B5" + "8DC13492C128B64F862E7800384C98A1303EA570D328C003E2B944A804B9794F" + "A5C6040881E61510E90C20F21DEA0A73E0DA5C1A2D178A48D76CC8FAA2ADA660" + "2A98B50AC197B40348A012E83A98EFF2B8D64900DE").HexToByteArray(); internal static readonly byte[] TlsClientServerEkuPfx = ( "30820AB602010330820A7606092A864886F70D010701A0820A6704820A633082" + "0A5F3082059006092A864886F70D010701A08205810482057D30820579308205" + "75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" + "010C0103300E04084BEC68D6BA25EEEE020207D0048204C8E534D459438245AC" + "EAC40458DAE1FDC42FB28605913F53F859CA1B7D62E385E48352F956A1B4D904" + "B796CE577F18A5E334990367542F7EB0806EDE06892812F914D62BC029E6637D" + "60BB10F125350DFC7F7702D68984F79C9192ECC07178330141B2CD8D88974F30" + "DD2CDF6F82F668AA5BF9F3201F1A8ED58B2546A2683260751F8254C3AC574ED2" + "8FBEF421A4C8B1C2CFB4691875314C06148A801036E39827BF3AA57F9FC32DB0" + "00C0BB9CCEB0E828651AD82E903B710DE378B00533994AEA596AD4FFD5B075E3" + "4BA54099F8FEA4AFCC469D071C48A0EF8BB58B46D3666A251188209AB7FE80F2" + "238EC6977280497ED7833283D3C49DD9546190404E1018C1179DDABBAF18D9B9" + "FE18D71FA4A87976F95A533FAE01E96057CDB05FF19DD14673AABB7FB5C3B01A" + "44F7D8265B320E846244E7C3EE65D01F4B468084F3890D92A065D745F41275D2" + "9650B00BF3CB7B4DB64D14A78591147F9FEA71DE4469DE58D1E90A40B5ABB151" + "B4F24BCA90E1966C9588D96627FE1F69ED8BC7A52F03BEED75CA8E90EBB811B1" + "37BABB34129C5E7AE44E1B6FE3A3DE8EC923F05E4A471BA0D27B134E5880CC4B" + "20CE7404CE9EB2C114C7018E811786A7FFF5FE6A2C7FAC4C4B2FA0CA6223E9D4" + "0A9D6567FB659857A83703D9E995CA2E1BC96FD6EAC678204661CD866530E61B" + "40533A011A250B6632760FD942A8A5741410C1BF0212D66085BB623F5C53A186" + "6699CE7CAD843C9325D54D260D254B3273717DEBE43F4F7FEDFC984546434CEC" + "46D70E3B888A85A11252DC12E7D50A32CAD5D4544C161F81BBCEF0D0DE893F25" + "C762FDCCDE1DF91262C815C925BFC6BA133E5CD42D32E7D2A6FB0BF22AE8482C" + "CEAE15070F1692D5BF3C2E2CCC02D77DF879C4D4F188B80870A234714B92197C" + "7A27F39A7E5366D7A2E99BCBF8BC5576DD627754EC4AEE2DE118EEDF7686D109" + "0B3A59E97051624D56224423BC9B4A2D7A85549596D4F981E29BF4C7F6CA8F38" + "2E4138BF515BB72CF4CF5D44F49274843BCCED64A9CA5A514E29C2DFE75CA4B2" + "FABACCA238DBA202AC6A996BDE4F79C9A568450C849BF12063C0CCEFF4B81057" + "A386697D217F4AD02ADCA127271CC5A3E5E9E3F6722D4173B83B39CEF5DF0BF8" + "F9630D575F3A99BF83BDA8A5A1A8CA5AF876F14BA5360DC6CBA5D1EC2F46C3E2" + "F14F87A03052C3EE4994C6B661248401F40EA0843F011E5186EF09B8917B4218" + "DF0352289252463E2DE1FFED603F330D80D6349C36FA9CF9B721069BDD833491" + "52FB1BA9F994507BB22CA076AE781FCDC5B1A487C9EE8BC2C83476260F61D866" + "0981A7BA1F5471F56C067BC6A3C1C6F4F76C72497DDD8AB961DB8FF673B00EB8" + "7C498624B2C46A184B6D4F248AC9307DF046DCFC70811402AF06468E7E07D6FC" + "353830F4F06B5902FD823A4A94099AAD9CEEC531CC544F74BCE62777F188CAC1" + "B819F6F0F449372E1B3ADC45514C8598A18427D2957511938CAC5439768A97C4" + "8D05A62660628DC2C16D1CFE73920C00B6DBEB4D66D1572F60817FBCCC3DDEB4" + "C5DCBB69799E4D3BC155FCF564B6AEBF25C7AC3A0F0CE7F4F2761738A7485236" + "8B4D950EA6672BA4615A9A040FA5166FF520948CA1D3649D9AD2317B8380FE90" + "4644F2C06F6173C8FB52A572FC50D69C273DBB63EBACA717441C2530CDEDAC0B" + "3796FAA4F9BAEC808A01F70E5B48E42B2AA49AFB65054EEFCB0F10072A38DA5E" + "3174301306092A864886F70D0109153106040401000000305D06092B06010401" + "8237110131501E4E004D006900630072006F0073006F0066007400200053006F" + "0066007400770061007200650020004B00650079002000530074006F00720061" + "00670065002000500072006F00760069006400650072308204C706092A864886" + "F70D010706A08204B8308204B4020100308204AD06092A864886F70D01070130" + "1C060A2A864886F70D010C0106300E0408FDE1F090274C2210020207D0808204" + "8071C27010C2CFFD78D49D28DBB5AEF4269926F1055E9DF0471FFD7077366628" + "DB87AC150E12BD5C636BE9A9CCAB194C87F32749D9544873A0C2360453A5293D" + "E03D5DCC1E3F12FDD89CF5BC37099A08DD9700CC0B6D1E351D5451386513E774" + "C3FAAB375F7A6731C8923C7979F8B283D33C09CF1DFAEFA9EC014845CD779C24" + "A1B085C2F9A8B3AF35197ECAD885B926463D785E9C192326FC6B956695970920" + "8B571E383D1083AD446DFEFADA128E247BC038DC74C43E9B5832922814DCEAED" + "F97E989BDB105642466FE2B2E2FEC3A19F556766DBBD0BCF9C5627876B1D2A19" + "42B3EC2DFA957DE74E669AC767811C6CE6133ED50F97D29FA002FAA0A72980A5" + "CC66C5FB86B1F657BE940489087D473AE6A5475A952B24A585254FC27AD50D80" + "0C3A77B13AC17401453645C03FFC66984FEA1ECC385852EFD7EB008971E31652" + "43A3F672FFB8590F756B4481EB5FFBBF5935C8062741D7AB38A4BE28D141FF16" + "6773ADE4EC3C021DDB5FCC43E2D03CDA4AD6BAC0EE63CA816089B8C971A3244C" + "6186BBEE09C09A31BC29DC8EAC665E7D9C6CC148C3FAD9028FF2E0A9F727DE1B" + "08AD8561D918677FB026A8EBD9BCFB0E106C058C6EFFD53FE13996B9C40F12B3" + "90DDD3CC63107CCA59F1CF861692629F4AFD7D3257218D9F888DF2E7A67BD601" + "2EEF48B82D09F01D1D1EDCEBEE878A771399D58EEA1D50C8F8ADCA3432696F2D" + "49D7253F064F4EC28C335853CD4EF9E72094517EFE61EB3E0A7F50451C1F9CA6" + "B95FCF62F36E6D79B16D99119C9E0D4AFFB36972E68A1FA2E2A099596176EA5D" + "C09756632BB4FC82136BB554FB32A2997DD982BDBD058F9990403FF786342C91" + "F117A98F0076CAB6AAF35F8FD5A5E795F9F3368049849D582E9950B42924BBC6" + "5EA3A0FB8FE87FD0B74C1621B52B673E92FD6475DCCB138425740AD1C006ECE5" + "3633C9AA2B02404384A31F7FE7DC9F41F2CDB4584283B48E6C5D1EE659316F2C" + "FAB3E6D5AEE5F0F986D223E7077C417BD890035E373BAC6B90E62451B14BB701" + "30C263872865F8975165452074A53FD036FC3930FF2F781D2805999DA7955BB6" + "4D4A98D0E67E4C18F73126177D047E89B24A409DEEA7B7B8CAABD0DD39DF3818" + "59E973360EFEE67D8FF9E24275E9F47D5A67E812DD68F8325603F3040180D85E" + "2EF61BD821CA666550E55F8A8C172D93315C6D7E14567BD9DE84A0C298A6A586" + "A63611495C66DD7D9AF83E20CEF31F3A3D3CC25553F2045FBB547C97C1AE43E1" + "F0147C116C82AB442562534E0898023CFB459DB66B7320DECA41E26477D76D5A" + "562BAC06023B778271311E3BC8E2D5ABD90515650A994CDAA99D38F6169D480A" + "122AD01731819FEEB8FE3111C1CF06FB9B5882EB74232B0CDA7DCAD2988FA9F1" + "8F4DCDC7DDC45983128E07F6687AD6C1FB219B3295AA74592B3D8B05C7D9851D" + "140A71CAD10D18EBCCDEB9C9243B39772E29D923D9D5014EA4CED9FE5C7859BD" + "6AAE8902726D5ECBB6C0D028728F316034F991CEA8F435FFDF35B26583C1CC44" + "959BAE4514EB478327BA76E6F9B759E176FDD8BFEDA8BDE6E7BF5E2F9C76CAB8" + "055DBE8A531FA77690A620BC5463431899B7577E3AEF0D382F31955AB5FCC951" + "973037301F300706052B0E03021A0414F2009473DB4B8B63778E28E68613246F" + "D53995810414A911A22D051F1BF45E7FF974C4285F6B4D880B08").HexToByteArray(); internal static readonly byte[] s_RSAKeyTransfer4_ExplicitSkiCer = Convert.FromBase64String( "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURhakNDQWxLZ0F3SUJBZ0lKQUppdWpocnpi" + "Sk9XTUEwR0NTcUdTSWIzRFFFQkN3VUFNR014Q3pBSkJnTlYKQkFZVEFsVlRNUk13RVFZRFZRUUlE" + "QXBYWVhOb2FXNW5kRzl1TVJBd0RnWURWUVFIREFkU1pXUnRiMjVrTVJJdwpFQVlEVlFRS0RBbE5h" + "V055YjNOdlpuUXhHVEFYQmdOVkJBTU1FR052Y21WbWVDMTBaWE4wTFdObGNuUXdIaGNOCk1UZ3dO" + "VEF6TVRjd05UVTFXaGNOTWpnd05ETXdNVGN3TlRVMVdqQmpNUXN3Q1FZRFZRUUdFd0pWVXpFVE1C" + "RUcKQTFVRUNBd0tWMkZ6YUdsdVozUnZiakVRTUE0R0ExVUVCd3dIVW1Wa2JXOXVaREVTTUJBR0Ex" + "VUVDZ3dKVFdsagpjbTl6YjJaME1Sa3dGd1lEVlFRRERCQmpiM0psWm5ndGRHVnpkQzFqWlhKME1J" + "SUJJakFOQmdrcWhraUc5dzBCCkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTN3Y01hNS9YTm14UEc2" + "NWwrZmtjV1RUcExzdURXTjIzZXVsMGI3OGUKK1RNNXpHbEUrakU0SHdJdXF0TTlXVytiRG5Ody9W" + "Ri82ME1STk9HWW5wWG55ZzZ3cEtKQXRxcm41aUpYY1RKeAowRUNUUHZBVWhLYWdzaHJMdVFCS1JH" + "U2pCdjVRQUg2cWMyZUZkdEJZS1dxVnBPSTBvUm5nREdkMTJOQVRiVVJECnEwUTJabHJEeVVJWnFw" + "VEZzaHlhdU00Nm84NmttZkI3Ty9TN0ZwbHE5S3lrZkxXTGhpTWVGVWZ2a0tSYnJpeVIKNnVneDRp" + "b09NWUpsR0Zzd2x5NXRyYm9HaGdtNTFKVEdDaXM1R29GcjlvZEJiWDFiSkFDai9peXM5bmYzaEpy" + "NApsRmZGVUJHc0hkeXpVRUYzZVZGSFo4U1lKdHRIdnlHdmJWWUxBcXpwTE15UEhRSURBUUFCb3lF" + "d0h6QWRCZ05WCkhRNEVGZ1FVdEd0aGs0LzVoa3ZZU1VzNU45b1p5ZkJ2cU5Nd0RRWUpLb1pJaHZj" + "TkFRRUxCUUFEZ2dFQkFIYnIKYzZFRUxpYmdsc09ReU9HYVlxUFZNa3JyWThhb3FveXVQUks1dzVP" + "dmlHVnVOb0R0dG1vbmRVek9pV1kybFlmUQpPak9UV29hb29qM0pQV1lrOEYrT1VrL05NRVB1NEFN" + "Nmx1dm9oNDRCNThBTXNYS0JaUjFXdFpncTRKVmQwb01lCm5ockY2Tkkzc3puaEFkZDdZQnozNzUy" + "bTV5bzFqQStKc0plVTdQRjlZL2F3bDFBWlp5VlZKYVBDdFpMY21KTFAKcVlWVHNlZ2NxVFlsK254" + "MDdHVitja1QxaGp0bjIvcFc5VkZMaXFHWUt4RkI0WXVOTnAvRWtUeFY5QTdJeGpDRgorQ1ZyVy9H" + "Z0NhbC9DVTE0b2tSaG5zVUxsQWw0RzBFeWorQy8zZE90alZQMjhWWFdacEJ2WXB6SWkrUHNxK1RH" + "ClEveU9MN2psMGFnT1dTcngwWnM9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"); internal static readonly byte[] s_RSAKeyTransfer4_ExplicitSkiPfx = Convert.FromBase64String( "MIIJqQIBAzCCCW8GCSqGSIb3DQEHAaCCCWAEgglcMIIJWDCCBA8GCSqGSIb3DQEHBqCCBAAwggP8" + "AgEAMIID9QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI2rQEBhq4HAUCAggAgIIDyEn+zCF3" + "wteqkmcbOFO7Aa2HbI8d1Dbp8M2QESYZhIZr/nX69etCuh4UewErHwwxfJYVQjhKO9NhWO4wB3UP" + "defCCrbrCmU2CIiTsgydNw8Qfyrdp4nMUNJ8AGCK9+atNX5MmLnLoFFT182SCZiJFVspDAlI/aEr" + "YNF3hvtYIJPce3om82XFHPotezxpFIma1MBuhQXEjcA12tfMAjPGdA1snqjMPPUOWK1f2Zpq7gCi" + "Q0E9fR3O2g4ut2FDpMAPIsG1HE4TlnShJ7qMT1wj70BcXstTVNFALw9emw4guIbbeqJmPrFKuqpY" + "7qi+Pk5AuBRMiR/g/A5ltJuP2ZemdlF79nI+Xz+uJPXzEHk4g4wueWCaR+lCeDhxGXqWrht4gVDV" + "sCp156WiDdfaUD5wkWPKihXlI42S65dvltHEG/NiD3zY324rAM+A8fAp4S1aILrqXjENehtncgCQ" + "6OX1RDvW2HD96pRwmdz0g+qGkQzQzzEXx2qdjqIO4nNWyedw/CrfEvC7mGCqoQ3x0mbHPtJNoRMS" + "AyNzkk2jQ7d8EpQJhbhgqsox0kDwBLXF4DlX9IhotCZBGI3em47PV9jFD7DRbU8G0nVjqb2Jo12d" + "5nkyvGPF+VIOxvqLO7yyMgptpEut2x6AhRsnCP+uPdzSCckPTJBlmGiHWIhRwWbLk77OLXOmF13v" + "TpE98cZojKH026CfmEtFrNVaMkC74YBBbHQR97Q6aTUjb0KIMpfJ6zeWFs88/E8h9B0K0B3RNg5d" + "qKjQhjix+j6KWAyhnP6iBSsFHtT30t1izEMPOK3Rn3lcB4NHOp3iRixAlb+abFPiCmA7Vo5ox7Fk" + "ns4+n/CeVCZaMie0+F9JFE9c9wxi7wYp9YGR28cAB7jNsVgQ5NJypNI1m7S74D7ivsN1D/4H7w6s" + "7+2NJyChQ6d1tKriDrpaFXBtuytieRGbmoI9hEqTvVRNGKHR/g1CJk705o+Iz25Trkhb8I7HOJmS" + "U6TS4Nm5eZxaqcnLiwwq2bkm0O4yeo92gX8aynMAKVqp4Zdf3nunGer+HIbp7vOA3i+3CscqgIY7" + "fFIQip75V3sr2acpQrSttY1sZiGQ7r7064g9WWgWmOloT8JaCPLzbqstA0q2+3nNsqOJItij8ig5" + "e04ZJdkHNQSVQ560A3Y0+6+w0AOWJJ5U3fDzG+E06jdO8+2Y0lzlBmDEnlUx34OD5RBg/tgAjC7+" + "SR9flnMTMwdyhfoKWMUYhtQsKk8vORGLjaJxyfZG33Ndt78nYazRPKW8G4sYdqi0bh4GMIIFQQYJ" + "KoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0B" + "DAEDMA4ECFwry53rQT+rAgIIAASCBMgEOQRCGM/ukQAEA4qrBattYzlC3tiHD0gqEh6SAxvPabaD" + "ISMLLoG0aZ0yjo+wDN7apOb9ohRIxoVyadJ9d9N4/nPIn1TnzHc7yQDTa1cktMSEszJgK8nWso+A" + "fQeljqqMmlTkryMiUdp+ekRu4TiDzq+zezQp20Lw5sfTVgGuMYfTUAYkB6LNzjbUw4S7/mEEcpN7" + "bKFKfcf3xi19yRwIO0ThLA9nF78Pq1QaORRpUuDi2zxSacHxN0wvM5HEIVEqL6+U7BgVAZF8r51x" + "1/+0do4O1XZpDcDQC1/yjW39dSFzWbNMOCm3aj87Tc5wurIFW1JqPmHc01k/Ks83dqSqscEBte/q" + "ez0XKtFGizUaxieo0ZQRHkLWE1wS7vmHIzhmYbRpSr3/WZO8u5Q5da3c1Gt5Jo6MAk3qp3gbowgp" + "I9vPFW4NIhq+XIx9rn8BdwKIpRwXGB5vK4aWh9GK4KBMk3mFVxWYa0ICf962R9VMzSvSLSSIJyuW" + "3UpbzXxQUjOVs99oKyfuDLyLQPeOVgBAVl5orSE2hcKAN2EZpHOF45TZsY9Z+HJaSwpaUDEPcvT/" + "9JD4uLhAcH7nQ5HX/Usp9nO8N5zC+ozBT1Hp8o0+g5pb8FBxh5NF0Guj3TlQ6VDXFX41lArdJy04" + "rZfWkGU9QE4VbMrBve/vyAiqdMIJ4nUCG0ghMr7VjFLPD4Gz7+9EZS2tft3tpu4VihM/TxSGgsWj" + "Fiyy5YZRU72KLZ+ztZvdLqYOc52/Xwxcgzdb2owMkpr3LAJONm8yXI+PFkOAVF+vkBdf4zNIzmja" + "ScsvnIhK7TwvlfAHEJBu8Q8pkO6sp7190WA6wOWhb7RovDMFMCJFaH7AVG8X7iu0fDxN/EqXwKH/" + "XTz/+FRGDIRmmS/VtavQEWkUsfSKKxfKT+glZ/sHyo5T6Cml3HaUkZ/aW8sQ7klIW1/uDepYE4ma" + "tA8znoDPT7fS5RM9cFfvn3Uh3KqfLB8SCBAiFkDQslf/vsVvFHxxIClA4++0oWwJ2rBibW3RdQPJ" + "acgd8BHuTy65TMZgbkthVBFa4p3Ne2c7Zbxhazw0Pt5Fqw/+kOp+o9chMxJsu75VMjzvVpMgRott" + "vn3c0jPj8olsiPn6mEWoYhdQQupTc3qmmhSHRILHc5FBY9UKoVRdg3fWeB8vf3OnQRqK1kvmc/yz" + "3+CUX9Kl998lYlp/YrFpqIv9A1LkyF8l43hXU56yuQTgaoYiMVTBEbdQ6/Luwg+ZAhLfl41G8MCS" + "Yn46mQgko9BYr9uIFpR78yzWbLnjm40vQ9mP2BE+5LxCg+QE0Frw7tpLHYrs1zIAhFw9nkZTDeTl" + "6VvOSmQegbw5uP3VV/SkkX2fO8DzU9M5nDDmK/CCklaGy2nzFAKrHIhsHhML4FWjiLxA0PGh6aBE" + "/2p+n9W45rLNqCOTejsbE5LVz/lUcDXbaCSKU28AdOUSSmv6f2hYV7idMmCORvpgKZmtjrjwVfGp" + "Rph7S0574FrS744psLILb+aSGaiNBPOFiBRRcUhPyVNL+Y4cOj/NMpgW6EsUpWpTJAr/1dnjFMbz" + "lz1b4B8KZkeQl3smXJaJz/7oU1jJ96QRYnGRyx6NYXOvu+v3b56g3Lo8MvBF59duDNcxJTAjBgkq" + "hkiG9w0BCRUxFgQUsdOM787p6dBPlEljE4Lazjja1NswMTAhMAkGBSsOAwIaBQAEFHcLzfQtoDAa" + "sbfisMs0Ll8CgjH2BAhMwg4eZANcOgICCAA="); internal static readonly byte[] s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Cer = Convert.FromBase64String( "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURhakNDQWxLZ0F3SUJBZ0lKQUs0cjJQai96" + "ZnF2TUEwR0NTcUdTSWIzRFFFQkN3VUFNR014Q3pBSkJnTlYKQkFZVEFsVlRNUk13RVFZRFZRUUlE" + "QXBYWVhOb2FXNW5kRzl1TVJBd0RnWURWUVFIREFkU1pXUnRiMjVrTVJJdwpFQVlEVlFRS0RBbE5h" + "V055YjNOdlpuUXhHVEFYQmdOVkJBTU1FR052Y21WbWVDMTBaWE4wTFdObGNuUXdIaGNOCk1UZ3dO" + "VEF6TVRjd05UVTJXaGNOTWpnd05ETXdNVGN3TlRVMldqQmpNUXN3Q1FZRFZRUUdFd0pWVXpFVE1C" + "RUcKQTFVRUNBd0tWMkZ6YUdsdVozUnZiakVRTUE0R0ExVUVCd3dIVW1Wa2JXOXVaREVTTUJBR0Ex" + "VUVDZ3dKVFdsagpjbTl6YjJaME1Sa3dGd1lEVlFRRERCQmpiM0psWm5ndGRHVnpkQzFqWlhKME1J" + "SUJJakFOQmdrcWhraUc5dzBCCkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTRJVUVaTmpMU1pja1Fi" + "WWJIUk1rek9lOW1lNzBWQVFHUjF0QWRLeTgKbHB2bkFxWkw1VGxPWHd5di94MktXbG9kVXlsOGpZ" + "dEhRc3lpb3BQRHF3QVBVUk5tdEZtQnVsTi95QW5Bc3JTZApqdWVHMWJCUjFZYVZzSFhpeDR0Mldy" + "SjFJcWtUbzIrTjIzb3ppa0w3ZWJzM0RtdDE4NlNLckJGVkdyODAvU3hYCndlMThiUWJQZ0RHYStS" + "MUczalFZakpPVGRFSk1rQzkzMUY0ZEFBYXZVcjgxWEJKNTg2T2dUZnY3SHhTMi9TMVAKS2cyNk4x" + "M1dWZEZRMmxieDVYYkZRZVpoVlovZ09uL2xDckVwM2NFcGdlSDdVSUt4ZmFrRGFQNHF5WDNhMXhx" + "YQpKU3hsa3liTWFwaWpiWVBiSmRzd3RKWkhIQTJxblhhTktwVDI4NldLRG5lWnlRSURBUUFCb3lF" + "d0h6QWRCZ05WCkhRNEVGZ1FVdEd0aGs0LzVoa3ZZU1VzNU45b1p5ZkJ2cU5Nd0RRWUpLb1pJaHZj" + "TkFRRUxCUUFEZ2dFQkFObFUKbW1EU0FrSk9rZkxtNlpZbFY3VTBtUEY1OXlJQjZReGJrSjlHUVVB" + "VjZrSnMwSG1lcUJRSncrQWRHRFBYaEV0dwo4ZDlGR0crZUtGeUdjWEY3Q1V4TU45ZGNjaThHYzFQ" + "WnA1UEZmbk04UVhZVTdLSFhRQWVlNm9yWW5FelBPZzMwCnljTklLbkF1L09Ram1ZcjRrci9zRnpk" + "Q2I1MDZRWkRxMnF0ai8wZThDYUY4T2RXdHNTWGIvcGtQM3liRzZqNHUKZzF2L0JtU1VYaUdWWFZx" + "M0JDUGZoeEowWGhyMnBBOS84b0VENjFBMG1aaGVmOUp5RTFhZFd5Q3RTaWMrelplYwpBcStDTnFs" + "R2o2cUpuRWhTaDBXVkdwMlRmMFhRaXBTTDk2REVCNlF2NlF4T3hpb0xNNG9zY2tKUEdhTGl5cmNj" + "CkZDUFYveUJyVm5Md0ZHR3NheFk9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"); internal static readonly byte[] s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Pfx = Convert.FromBase64String( "MIIJqQIBAzCCCW8GCSqGSIb3DQEHAaCCCWAEgglcMIIJWDCCBA8GCSqGSIb3DQEHBqCCBAAwggP8" + "AgEAMIID9QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQITLms5nr095wCAggAgIIDyPyxib5c" + "oCEPC3OpfmCzzieARKf56sQZU31qlDJNDet7v1R68T7X9vu236kHOphKvqedPVNXKEPpaQXIxkSY" + "Hus2Xg7Zv7jwW99/A/coitXNEyOnqdv3vYRu2f69iwZJQmiPsQKC8uVbDBgPBZPPe+tgkY5e7dqZ" + "mwob4oJ3bjKR4cYPk8QkSOxgBXHLNZ0Cv3fjiAVKHnPGSo5pyvwwUtSp0bBXniyq9wnzYheiLBSg" + "S99M1HVvnbbFuhZYeyTP6gqRSda9bgVa0NNGhFYKjnw0H2K2KRtIskL/P4vcxZWTSdLNxZKQDfgx" + "R0Om+f8qFiDzaW5jo3ljJ9pZKrHWo0tDAhSBicOvFsNTX3zu9ldRJLyHO7SZObvHr3BCa6LoXRNA" + "BEhYmihmKwCv0dXfUgEZ6BSwSeHdNEWSVQhLLHI5oL2eRjHOCa8q3Md9GDn1hdnwUQftmvn9w2Dg" + "EhJxJe+DjhLquh+fB+JXFnrNg5s0birl1RPL7wsdadGBav9UhpRcIgxux4eaOkkGE8mySOxBY66s" + "BV6upSxJf+KAQXBQOqMYoC5wK6hXzllAWLDjpEHuU2q40bTWoUZk2lw8rSzxW/mhLoVl21Ix3x6h" + "Hm8VUaGkOsQbpMhI68B47yNgnkUyX5FciFtxnV7cxAqxjtaq5yO7gjzUSs7uyV3pYhdL95f1tlrD" + "goBz/OKSFZYnII8UnTQniFdqZc6rhKnJpTvuVJy6I3Os9DrJpZ34MagAkb6lwIy/BqV4hPDx2AaQ" + "j3P/Qk4xPq0EcbUSuDZHAe4nLygpnMtDynM5UDcUjLLEtGIX9MpUtAPUtZEH/ZRtWF0wIkvFCUDc" + "Gh6v8bZtRYvCd4Vbnf99ueRKjyA2PREcriO+gsdEUd+rmkBwCMPPRmIjX8tr9yuqM9kRlmvzYbBB" + "3RcUsfyl9I39S1kJQkrr5mOH2hVMTl6UQ70jM+RBet4FJN3TUWaoBNm5m2+9FLpL8GcFPH//WPnw" + "S2AqXl+iTysAUxqjtZ8jWkyl6DmybKHxPbR6Vy/6w/2WOUQOOsnFADm9NJPV8TE1Z6qnhlh4f7fz" + "zAue+vnkZE7920JN/ThEkreIJ1vvyfPQsfo5XSoK7SA7OlP0JX4bKEyWsahFzmFOaGNJUCKTR/gh" + "JVB6CcgrvyAE4BFsZeq79teOCKVZiseKwtmarTCMGQOdo+h5ceWXnII0gjndwcZbzURh3sj86AS+" + "GXk69sNKC6HvbineMu/oL8ZgsifD/OTTRC5ewXENyoF57vMCkFV19K95PNTN6icGEcYeMIIFQQYJ" + "KoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0B" + "DAEDMA4ECITzIA3DVAowAgIIAASCBMhUF7mWIkOeh/4zd9n71iNtHgyZIm90cF31YRHS3syGcsAI" + "B4LH0wnHthG1u5GaEhTjMzBTr96hFkOFwmCW+8Kbg25oIcy12aren2Rn2LPkoHmmV/aA5ot7bbsK" + "2vTgbae4GbMwXb0oBMKLU3wzKcYyluhVGVket2+szUHUsMKZxhFUThkvZqnNC1BYKDidiCP0npEb" + "bgX4ARBEB++bL01YFvQbX/72JSPKTtvTs3aoYTlfoklwUrxSw60/wYn+3y8KVyBIkdZKDVKS0AbF" + "uNEQZYmyf4AiSv7q4h6WKfwI9ojl7wv9k0/h/a+x+8rAITHdX/ZaSNcmoWa/zCKWNO+YntvrRxLZ" + "xGE4t3S/4h32bbo+dDD5iLucuUGVMFt6b9CBph8+QYIbte3zjQPjPWY1YexRI4LqiK5/3ZFCRPJK" + "Eq4bYmhur34RmQ9vZy7NfANgW+lJVit1vfOMHjQj62svkbabMjVrWVhnpAJ7jhBoNRzbggY/Ehhq" + "G5BXY6fEjwPWFivHM0gmmBX5VlCTmhJck2sCJ4rKSpc9ZB4J6ucPH3wHEyO1HIDgB8yI47v4CZeB" + "XyfIrozivPn7OCmItD4tUdH7w4/BJxNOMZ+Gpoz5tGWoeMcPWzb3JoUBJgpZ7YnqFbG8I1lTlG6P" + "EbhNuyXtB83R65CAASteHww7PMfZDmUQO/KJwNvmZFPNox4IocTKLf7cOMXt6NR5hPQpc/tecDdu" + "QzQG1nEITq0MP8Ex3YQgu37gfpYNiRAki7yKrwzYpwVrUSwap0RPIn4+UxwoINXngwZTmNkhXEr+" + "sfW8uiB8P5ZrhqF+9dCGBHKAAy35NMEGXXHK79YOrnP2qNf8IbfnopwnZNYSniKFF7XvPmjiVANa" + "ARQ8wWIUbhsweZIz9dz0GH7mdk877o0k1xrqpXagAeaF7wwAz/HLFbIG4+XXD5fFjkqaFpuTYjOt" + "FgneN9wXDwgvQWyqPbjx/kJBD5k+UAW1r1z+LDwD/VdPMJ5bdfWa5QFCIxWw137VsieGXNZvB57Y" + "hdI2D3LKk+0DhGJjGTxy6g/ZTwvGUlPPe20+Ip2+zSoKhE2YVBAbsy36+cr77buOPg8L5aNqUg5l" + "rIYe5eLADLg8Unavy54ySIy2pZ0gX2G2eGQebwAIQEqDYBIRUyiEhbjGKprTTRQj6Ho3M/mmHOKM" + "fHZeWT+BGOAa0+eCz436QS7YsXl2AOwFBqDI6ZONYTBRu2WLvuK3nbwb+h1Rv6/pd7NGI6AXJBKJ" + "1+iBLGl5HBoOIYmpG+yGgajXGXDVqkRGESUnrJQGlXbwq00MFvtKbGI9+iQBgw4pbrUzc5xId0OZ" + "1ynSTYrKzaGfi1KqMj2dQbQ+b0SshD/BVrBtYYVEnY9LaPokHna0cYcUGXxnycesk2Av0kQziEmH" + "vltVZDj1LyMBJzF/auHY+Pbx4NIN33fOdKXByQSE4ulZqgsftn77B25yxwjO2Sks+ess7+pGBbO1" + "ikOqm6zol92lwRibj8bbbva86Sd3yd846Yxc4QRcSldTPMOQsBrfs8ZetusRCiONXb+gKDne/Z/N" + "u94mkxMkJvLRJHPesvNkxiXYhC0mSFl9RDSkIgrRJ2uRSxv0V5OdcAiCi3d98OlrIYkxJTAjBgkq" + "hkiG9w0BCRUxFgQU++MZ+0nVwxEM/9SdcPKsQcAk4ycwMTAhMAkGBSsOAwIaBQAEFFNlHKZQXjbm" + "f0PE6idyhcH963CyBAiMLpuBSuzCdgICCAA="); internal static readonly byte[] NegativeSerialNumberCert = ( "308202C2308201AAA0030201020210FD319CB1514B06AF49E00522277E43C830" + "0D06092A864886F70D01010B05003014311230100603550403130953656C6620" + "54657374301E170D3138303531343231303434385A170D313830363133323130" + "3434395A3014311230100603550403130953656C66205465737430820122300D" + "06092A864886F70D01010105000382010F003082010A0282010100E2D9B5C874" + "F206A73C1FC3741C4C3669953929305CF057FF980DE2BAAEBA5CF76D34DE5BF8" + "ED865B087BF935E31816B8B0DEDB61ABEF78D5CBC5C3389DBD815ECF7BDDC042" + "BD21F68D9A7315671686613260B5D3505BC7C241C37C6E42C581228965B5D052" + "B8ED3756966C6B678CDF647E5B659E5059915B16EF192BD313F6423FD487BBB4" + "06BA70A7EDA7DBC55E15F1D93017BC92238D22DD9A15176A21F1BF7CF7AD280F" + "7C32D76C8B136F0FBD0A89A373CF194CB5A0CF7AC1FA8098458290FD66311BB8" + "DB17E9CB70D6668A8926F26198586C796C61EEDBFD376525130BAD2C452B6A66" + "97AF7FE8F91408785C20DE79F4AD702197734328B4642FB898FF730203010001" + "A310300E300C0603551D130101FF04023000300D06092A864886F70D01010B05" + "00038201010057E4CE63680B165CD3DDAF5CC84F31CBC6C2CCDCBE33893A3FA7" + "01781BBB9F003C0E301216F37D4E9C735F138920121983728EA88324DBEC66C7" + "824BB25EC534C3AA5999C8A6D9393F9B04B599A94B415D0C0392E0FBE875221D" + "A4348FE76ACBE5D845292AC475A9104052CCEF89390118E8EA8051519F423276" + "164D8BDD5F46A8888C540DF5DD45A021593A0174BB5331223931F7756C5906A1" + "94E7FF2EFB91D4CBFA4D1D762AE0769A07F2CC424692DB37131B2BEBDB3EE4BE" + "07F9B1B12B5D368EC9317237CAB04D5B059F9226C972BADBB23CA747A46581D4" + "9240E6FC0F2C8933F1844AD5F54E504DDAA3E87AE843C298DED1761035D2DFBF" + "61E1B8F20930").HexToByteArray(); internal static readonly byte[] NegativeSerialNumberPfx = ( "308209C40201033082098406092A864886F70D010701A0820975048209713082" + "096D3082060E06092A864886F70D010701A08205FF048205FB308205F7308205" + "F3060B2A864886F70D010C0A0102A08204FE308204FA301C060A2A864886F70D" + "010C0103300E0408F693A2B96616B043020207D0048204D8BEC6839AED85FA03" + "2EAF9DED74CE6456E4DB561D9A30B8C343AF36CEA3C7F2FA55B1B7C30DBF4209" + "58FEB61153386DCE8B81DCC756E06EC872E8B63FD6D8341123FDAE522E955357" + "76B5A09941595C79404E68729389819D05459515314167A9E2585F3B2C8F9F24" + "860BA42612DC492137051063A8EC8CBBC3D0ED59B92D10E6612C0C9AD5AE74DD" + "999007CFEDA7A1AD2A2D5C25E41201F5A810D2654A3DA1648AF5D9EBBCFDFEEB" + "FF8BC78A7BCE26EF0ECB1B0F07B33FB777160ACDF3DE00267398D771A35740AF" + "661B189CB7394C02599417AF601231F3B6F40869E2DA8909D8A6D9565CFA389C" + "5A002193B3CC374D973F0A587697CE6812126E3BC390093E56B671E8FA77E1C1" + "E56AE194AD7695BED88A1139AA149F4E0875121995661B4133E9242FCAAF8A1F" + "5721A055FC523EFEA4EEA98B6FB48EF07891B2E80D6EAC824FE9BBFBCB6A72A9" + "52F12C3E3DE63F33F9A126BAC8FB0C7F2BF98A781598E6FE5A86409F4F22249F" + "4A38B4670A2BF0EF93B0990AF33672CCAEFF15BB5813ECEDFDA38CA2BEEDAAA5" + "2B880609057B3FC728F6D1964B7185A933B1526666FBC42C1B5D9A6FF3E2B3BD" + "1BB8893BB6B9170BD4D7C6EB47C573FA90E19971017A6FAAD2B36CC746EBB238" + "2211248404A09E2ABBC546D85B212286334E164FE24E03BAE053C3C12FA21F29" + "FAC8A69F0EEBC688FB50834B5D7F2CB7CECC9BD5D6C06200AAC11B33AF2B6E11" + "1F3853AEFBC086881561860093AE6C66A488BECE95CC80ECCABCFE91BDD302EC" + "B86DF4B99530ECD707943E76ECA51E07DC109B9B788D1C0664C560352B251FCF" + "D9F57C6C18DEDFB9B848A2A57A96B0BEB6C20FEFADAAE468D96B48AB061F6BE6" + "194865E676009BD48E5951C534C05A4C4186DF7CF85B596E2F4FA2495440071B" + "C13ECE7AF0E58FA13B53DF115BBAF846A5E2AF1F71B3F8AE895C62ABD90FBEBB" + "815993D122B4B6816DF95C8097E9A1FC66F0181441B3BC3320BBABEE02004138" + "93BBFEB480123A28B14AD4D4B8C918B851DA11C4347C8D1E46B2F211F0E6F049" + "0674C2B1C2F6AC020D79E50A45363AD54D5CD2D6668DE917111111E380ACC015" + "3CF5A0E3B25A4DF35305308FA2A5C0FFFFA31F6699D5F0699DD82AA5502EA6C3" + "B6B782FDEDF5515DBA4D1FDB295A77119D49BC098D35A45E8DB2C88B7C97DD1A" + "BB54B0D2EA27AD7B7A79D3C707C482376F8F612129C48024F4A1065BFCFAC2FE" + "A176AAA2E0064BE2E77D9E3BCEA0AA732B59DB213A9A0EC972E376D8ACDE5BB6" + "4C668B0E24BFE9479BE7574B07D4BEADF821769720A0B7557411826C97206B3D" + "176262F4BBF64631ECBD31418487588773E39D46784A4361E31742333BE1DE2A" + "BB0331011CA400795E306EDA88F82C78B6906B22E5D0CF68F9F349B9725178BA" + "6B03D972E27C8EB376BE51206DE070FA45EE430D6CE17FD2744A7830E7A8E2C4" + "C5033D39BFB14D74214ADE082371C49246540B0593487B0DC95BC9B887FA2222" + "250D59EB2BB04983AD59004E3921ADCADB30E5C713B9B5FC31A6FD97D6694483" + "2E29DAD105CF81265F8149B5EB32192CD0FA45F53621AE7A4D372ECCEC013D08" + "B7D1BE73E5D3331236E90DE00A3AC3044F1A5462C9E84CB621A9C68C8B954824" + "B684ED3DFC2D2839B19AF443F54ECBF3EC580BADC3CBECFDFE05BDCBA201C984" + "C7DDE01EF79E57C5E8EAF9C1E4C8D48DCDA8C6A51F8C0DECABFC4BA6B776C4C8" + "BA0110C6D5CEEBC7476E86D4710F5E773181E1301306092A864886F70D010915" + "3106040401000000304F06092A864886F70D01091431421E4000380038003100" + "3800350063003300300061006100660038003400370036003500610037003700" + "32006600610036003400350035003900630062003400320064307906092B0601" + "040182371101316C1E6A004D006900630072006F0073006F0066007400200045" + "006E00680061006E006300650064002000520053004100200061006E00640020" + "004100450053002000430072007900700074006F006700720061007000680069" + "0063002000500072006F007600690064006500723082035706092A864886F70D" + "010706A0820348308203440201003082033D06092A864886F70D010701301C06" + "0A2A864886F70D010C0106300E0408EBDF03E906A5A3C1020207D08082031043" + "B764B7A7FA6203394F0625BB0D59B39D3F28197972CBEC961476D76BE560A312" + "1ED025A9455F39C33B2ABC1FA897EC29FAF01970321069F8CA20EE4DF6F9E98B" + "0DCB3A290DFF4B9B1D151E4AE3AFD7D7383B40B292B0F369A47823A7C175F6CE" + "A327283B8B33712B88F06ADDA6CD626036765E9E102E110C8E44EA75E53C5FEB" + "661B08D7A9C06B59A35E76F293E8EFA64AF425B877D0321C13BA0079DA14D3A9" + "A76EB69CF22E4D427A35C7391B650B822FA91FF0D3DFD1E037C34E2F1110C1A7" + "F88A35E560422AE31203ED22BA74D1A6F8FB2AB5DA6E5E66633B7081E6F5681E" + "DE01BD28E6DA6B6E0C1444A010DE229D6AD6E44E99400EC22EF1DD6E7E805503" + "4B1A29ACD78F6D561E2DA35B84DA1F08BCDD0A74AF49E509744A91F4304F7EEB" + "6231C18EC9159D31114183C0B9621AA227663AC67A5DB4B0982B539578DF0ED7" + "6B577FD370FA4330E2DFAA015E1E6E2E4C6B71967071390D4B1CD061F567D072" + "2BBBE027C1350B1679D1AE7DE7522AF62960403C15F1B75DC2AA0A1339051FA9" + "E16692773046ABE0EEC29C1E6FE0ADEA33F7F878B004BC161D362ABDCD2F9992" + "82D967B9FA46BCBF0D12CB6659FB2BABA258DE158F51F961CAD7AB5D68D6DFE8" + "5E0DC6F043C4AB203E2F549EE0A3C2E25E13CD1462CD03AA3DB4689BA1DD0D8E" + "D8293DA3D195901405154E98999E60BBA39A543E64963BE607BD48275508946B" + "D27DA136C9F53C692DDC81FD3F6AD56419589716EF6F3A66A35049B29D438D5C" + "F778961F74E954CBE1395D8A98971C30C3941CFCF2D3B8851C819D79D164FC71" + "CA414798F4FFF3A6362A59AA17F543B5B4B2F2B7E14ED48B8ABEEB68469161B0" + "6D2233257291C6F1B67D0BDC2422F3E04213CA29EB648219A6C3E339C1352E55" + "F6D8749592723934693DD54F1D098DACFE9D308556B060CCC75D2F7AA8DDEC3C" + "B1B127DE82AC8489FEFA4A9F09D49C919F703236036853D5E802975D4B3DA619" + "EF90CF53AA38D0D646B69E75751DA833C619337722CA785477343614ACB67AF4" + "427E3EAFAC5900F0A573512BD81F1A86A848321309156093665E39193B0867A0" + "5C86500AF2760F8A87DB8E6E5FA2753037301F300706052B0E03021A0414AA38" + "B6B4257EBA3E399CA9EDD87BDC1F82FBF7D70414B796F49E612D1A2B5A0DEC11" + "608A153B5BCD4FE9").HexToByteArray(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.DirectoryServices; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.PowerShell; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation { /// <summary> /// Deals with DirectoryEntry objects. /// </summary> internal class DirectoryEntryAdapter : DotNetAdapter { #region private data // DirectoryEntry(DE) adapter needs dotnet adapter as DE adapter // don't know the underlying native adsi object's method metadata. // In the MethodInvoke() call, this adapter first calls // native adsi object's method, if there is a failure it calls // dotnet method (if one available). // This ensures dotnet methods are available on the adapted object. private static readonly DotNetAdapter s_dotNetAdapter = new DotNetAdapter(); #endregion #region member internal override bool CanSiteBinderOptimize(MemberTypes typeToOperateOn) { return false; } /// <summary> /// Returns null if memberName is not a member in the adapter or /// the corresponding PSMemberInfo. /// </summary> /// <param name="obj">Object to retrieve the PSMemberInfo from.</param> /// <param name="memberName">Name of the member to be retrieved.</param> /// <returns>The PSMemberInfo corresponding to memberName from obj.</returns> protected override T GetMember<T>(object obj, string memberName) { PSProperty property; DirectoryEntry entry = (DirectoryEntry)obj; // This line must precede InvokeGet. See the comment below. PropertyValueCollection collection = entry.Properties[memberName]; object valueToTake = collection; #pragma warning disable 56500 // Even for the cases where propertyName does not exist // entry.Properties[propertyName] still returns a PropertyValueCollection. // The non schema way to check for a non existing property is to call entry.InvokeGet // and catch an eventual exception. // Specifically for "LDAP://RootDse" there are some cases where calling // InvokeGet will throw COMException for existing properties like defaultNamingContext. // Having a call to entry.Properties[propertyName] fixes the RootDse problem. // Calling entry.RefreshCache() also fixes the RootDse problem. try { object invokeGetValue = entry.InvokeGet(memberName); // if entry.Properties[memberName] returns empty value and invokeGet non-empty // value..take invokeGet's value. This will fix bug Windows Bug 121188. if ((collection == null) || ((collection.Value == null) && (invokeGetValue != null))) { valueToTake = invokeGetValue; } property = new PSProperty(collection.PropertyName, this, obj, valueToTake); } catch (Exception) { property = null; } #pragma warning restore 56500 if (valueToTake == null) { property = null; } if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) { return property as T; } if (typeof(T).IsAssignableFrom(typeof(PSMethod))) { if (property == null) { #region Readme // we are unable to find a native adsi object property. // The next option is to find method. Unfortunately DirectoryEntry // doesn't provide us a way to access underlying native object's method // metadata. // Adapter engine resolve's members in the following steps: // 1. Extended members -> 2. Adapted members -> 3. Dotnet members // We cannot say from DirectoryEntryAdapter if a method with name "memberName" // is available. So check if a DotNet property with the same name is available // If yes, return null from the adapted view and let adapter engine // take care of DotNet member resolution. If not, assume memberName method // is available on native adsi object. // In case of collisions between Dotnet Property and adsi native object methods, // Dotnet wins. Looking through IADs com interfaces there doesn't appear // to be a collision like this. // Powershell Parser will call only GetMember<PSMemberInfo>, so here // we cannot distinguish if the caller is looking for a property or a // method. #endregion if (base.GetDotNetProperty<T>(obj, memberName) == null) { return new PSMethod(memberName, this, obj, null) as T; } } } return null; } /// <summary> /// Retrieves all the members available in the object. /// The adapter implementation is encouraged to cache all properties/methods available /// in the first call to GetMember and GetMembers so that subsequent /// calls can use the cache. /// In the case of the .NET adapter that would be a cache from the .NET type to /// the public properties and fields available in that type. /// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass /// to the properties available in it. /// </summary> /// <param name="obj">Object to get all the member information from.</param> /// <returns>All members in obj.</returns> protected override PSMemberInfoInternalCollection<T> GetMembers<T>(object obj) { DirectoryEntry entry = (DirectoryEntry)obj; PSMemberInfoInternalCollection<T> members = new PSMemberInfoInternalCollection<T>(); if (entry.Properties == null || entry.Properties.PropertyNames == null) { return null; } int countOfProperties = 0; #pragma warning disable 56500 try { countOfProperties = entry.Properties.PropertyNames.Count; } catch (Exception) // swallow all non-severe exceptions { } #pragma warning restore 56500 if (countOfProperties > 0) { foreach (PropertyValueCollection property in entry.Properties) { members.Add(new PSProperty(property.PropertyName, this, obj, property) as T); } } return members; } #endregion member #region property /// <summary> /// Returns the value from a property coming from a previous call to GetMember. /// </summary> /// <param name="property">PSProperty coming from a previous call to GetMember.</param> /// <returns>The value of the property.</returns> protected override object PropertyGet(PSProperty property) { return property.adapterData; } /// <summary> /// Sets the value of a property coming from a previous call to GetMember. /// </summary> /// <param name="property">PSProperty coming from a previous call to GetMember.</param> /// <param name="setValue">Value to set the property with.</param> /// <param name="convertIfPossible">Instructs the adapter to convert before setting, if the adapter supports conversion.</param> protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { PropertyValueCollection values = property.adapterData as PropertyValueCollection; if (values != null) { // This means GetMember returned PropertyValueCollection try { values.Clear(); } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode != unchecked((int)0x80004005) || (setValue == null)) // When clear is called, DirectoryEntry calls PutEx on AD object with Clear option and Null Value // WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, // we need to catch this exception here. // But at the same time we don't want to catch the exception if user explicitly sets the value to null. throw; } IEnumerable enumValues = LanguagePrimitives.GetEnumerable(setValue); if (enumValues == null) { values.Add(setValue); } else { foreach (object objValue in enumValues) { values.Add(objValue); } } } else { // This means GetMember returned the value from InvokeGet..So set the value using InvokeSet. DirectoryEntry entry = (DirectoryEntry)property.baseObject; Diagnostics.Assert(entry != null, "Object should be of type DirectoryEntry in DirectoryEntry adapter."); List<object> setValues = new List<object>(); IEnumerable enumValues = LanguagePrimitives.GetEnumerable(setValue); if (enumValues == null) { setValues.Add(setValue); } else { foreach (object objValue in enumValues) { setValues.Add(objValue); } } entry.InvokeSet(property.name, setValues.ToArray()); } return; } /// <summary> /// Returns true if the property is settable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is settable.</returns> protected override bool PropertyIsSettable(PSProperty property) { return true; } /// <summary> /// Returns true if the property is gettable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is gettable.</returns> protected override bool PropertyIsGettable(PSProperty property) { return true; } /// <summary> /// Returns the name of the type corresponding to the property's value. /// </summary> /// <param name="property">PSProperty obtained in a previous GetMember.</param> /// <param name="forDisplay">True if the result is for display purposes only.</param> /// <returns>The name of the type corresponding to the member.</returns> protected override string PropertyType(PSProperty property, bool forDisplay) { object value = null; try { value = BasePropertyGet(property); } catch (GetValueException) { } var type = value == null ? typeof(object) : value.GetType(); return forDisplay ? ToStringCodeMethods.Type(type) : type.FullName; } #endregion property #region method protected override object MethodInvoke(PSMethod method, PSMethodInvocationConstraints invocationConstraints, object[] arguments) { return this.MethodInvoke(method, arguments); } /// <summary> /// Called after a non null return from GetMember to try to call /// the method with the arguments. /// </summary> /// <param name="method">The non empty return from GetMethods.</param> /// <param name="arguments">The arguments to use.</param> /// <returns>The return value for the method.</returns> protected override object MethodInvoke(PSMethod method, object[] arguments) { ParameterInformation[] parameters = new ParameterInformation[arguments.Length]; for (int i = 0; i < arguments.Length; i++) { parameters[i] = new ParameterInformation(typeof(object), false, null, false); } MethodInformation[] methodInformation = new MethodInformation[1]; methodInformation[0] = new MethodInformation(false, false, parameters); object[] newArguments; GetBestMethodAndArguments(method.Name, methodInformation, arguments, out newArguments); DirectoryEntry entry = (DirectoryEntry)method.baseObject; // First try to invoke method on the native adsi object. If the method // call fails, try to invoke dotnet method with same name, if one available. // This will ensure dotnet methods are exposed for DE objects. // The problem is in GetMember<T>(), DE adapter cannot check if a requested // method is available as it doesn't have access to native adsi object's // method metadata. So GetMember<T> returns PSMethod assuming a method // is available. This behavior will never give a chance to dotnet adapter // to resolve method call. So the DE adapter owns calling dotnet method // if one available. Exception exception; try { return entry.Invoke(method.Name, newArguments); } catch (DirectoryServicesCOMException dse) { exception = dse; } catch (TargetInvocationException tie) { exception = tie; } catch (COMException ce) { exception = ce; } // this code is reached only on exception // check if there is a dotnet method, invoke the dotnet method if available PSMethod dotNetmethod = s_dotNetAdapter.GetDotNetMethod<PSMethod>(method.baseObject, method.name); if (dotNetmethod != null) { return dotNetmethod.Invoke(arguments); } // else throw exception; } /// <summary> /// Returns the string representation of the method in the object. /// </summary> /// <returns>The string representation of the method in the object.</returns> protected override string MethodToString(PSMethod method) { StringBuilder returnValue = new StringBuilder(); foreach (string overload in MethodDefinitions(method)) { returnValue.Append(overload); returnValue.Append(", "); } returnValue.Remove(returnValue.Length - 2, 2); return returnValue.ToString(); } #endregion method } }
using System; using System.Collections.Generic; using System.Text; namespace Reusables.Adapter.System.IO { public interface IFile { /// <summary>Copies an existing file to a new file. Overwriting a file of the same name is not allowed.</summary> /// <param name="sourceFileName">The file to copy. </param> /// <param name="destFileName">The name of the destination file. This cannot be a directory or an existing file. </param> void Copy(string sourceFileName, string destFileName); /// <summary>Copies an existing file to a new file. Overwriting a file of the same name is allowed.</summary> /// <param name="sourceFileName">The file to copy. </param> /// <param name="destFileName">The name of the destination file. This cannot be a directory. </param> /// <param name="overwrite">true if the destination file can be overwritten; otherwise, false. </param> void Copy(string sourceFileName, string destFileName, bool overwrite); /// <summary>Deletes the specified file. </summary> /// <param name="path">The name of the file to be deleted. Wildcard characters are not supported.</param> void Delete(string path); /// <summary>Decrypts a file that was encrypted by the current account using the <see cref="M:System.IO.File.Encrypt(System.String)" /> method.</summary> /// <param name="path">A path that describes a file to decrypt.</param> void Decrypt(string path); /// <summary>Encrypts a file so that only the account used to encrypt the file can decrypt it.</summary> /// <param name="path">A path that describes a file to encrypt.</param> void Encrypt(string path); /// <summary>Determines whether the specified file exists.</summary> /// <returns>true if the caller has the required permissions and <paramref name="path" /> contains the name of an existing file; otherwise, false. This method also returns false if <paramref name="path" /> is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of <paramref name="path" />.</returns> /// <param name="path">The file to check. </param> bool Exists(string path); /// <summary>Sets the date and time the file was created.</summary> /// <param name="path">The file for which to set the creation date and time information. </param> /// <param name="creationTime">A <see cref="T:System.DateTime" /> containing the value to set for the creation date and time of <paramref name="path" />. This value is expressed in local time. </param> void SetCreationTime(string path, DateTime creationTime); /// <summary>Sets the date and time, in coordinated universal time (UTC), that the file was created.</summary> /// <param name="path">The file for which to set the creation date and time information. </param> /// <param name="creationTimeUtc">A <see cref="T:System.DateTime" /> containing the value to set for the creation date and time of <paramref name="path" />. This value is expressed in UTC time. </param> void SetCreationTimeUtc(string path, DateTime creationTimeUtc); /// <summary>Returns the creation date and time of the specified file or directory.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the creation date and time for the specified file or directory. This value is expressed in local time.</returns> /// <param name="path">The file or directory for which to obtain creation date and time information. </param> DateTime GetCreationTime(string path); /// <summary>Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the creation date and time for the specified file or directory. This value is expressed in UTC time.</returns> /// <param name="path">The file or directory for which to obtain creation date and time information. </param> DateTime GetCreationTimeUtc(string path); /// <summary>Sets the date and time the specified file was last accessed.</summary> /// <param name="path">The file for which to set the access date and time information. </param> /// <param name="lastAccessTime">A <see cref="T:System.DateTime" /> containing the value to set for the last access date and time of <paramref name="path" />. This value is expressed in local time. </param> void SetLastAccessTime(string path, DateTime lastAccessTime); /// <summary>Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.</summary> /// <param name="path">The file for which to set the access date and time information. </param> /// <param name="lastAccessTimeUtc">A <see cref="T:System.DateTime" /> containing the value to set for the last access date and time of <paramref name="path" />. This value is expressed in UTC time. </param> void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); /// <summary>Returns the date and time the specified file or directory was last accessed.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in local time.</returns> /// <param name="path">The file or directory for which to obtain access date and time information. </param> DateTime GetLastAccessTime(string path); /// <summary>Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in UTC time.</returns> /// <param name="path">The file or directory for which to obtain access date and time information. </param> DateTime GetLastAccessTimeUtc(string path); /// <summary>Sets the date and time that the specified file was last written to.</summary> /// <param name="path">The file for which to set the date and time information. </param> /// <param name="lastWriteTime">A <see cref="T:System.DateTime" /> containing the value to set for the last write date and time of <paramref name="path" />. This value is expressed in local time. </param> void SetLastWriteTime(string path, DateTime lastWriteTime); /// <summary>Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.</summary> /// <param name="path">The file for which to set the date and time information. </param> /// <param name="lastWriteTimeUtc">A <see cref="T:System.DateTime" /> containing the value to set for the last write date and time of <paramref name="path" />. This value is expressed in UTC time. </param> void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); /// <summary>Returns the date and time the specified file or directory was last written to.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time.</returns> /// <param name="path">The file or directory for which to obtain write date and time information. </param> DateTime GetLastWriteTime(string path); /// <summary>Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.</summary> /// <returns>A <see cref="T:System.DateTime" /> structure set to the date and time that the specified file or directory was last written to. This value is expressed in UTC time.</returns> /// <param name="path">The file or directory for which to obtain write date and time information. </param> DateTime GetLastWriteTimeUtc(string path); /// <summary>Opens a text file, reads all lines of the file, and then closes the file.</summary> /// <returns>A string containing all lines of the file.</returns> /// <param name="path">The file to open for reading. </param> string ReadAllText(string path); /// <summary>Opens a file, reads all lines of the file with the specified encoding, and then closes the file.</summary> /// <returns>A string containing all lines of the file.</returns> /// <param name="path">The file to open for reading. </param> /// <param name="encoding">The encoding applied to the contents of the file. </param> string ReadAllText(string path, Encoding encoding); /// <summary>Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.</summary> /// <param name="path">The file to write to. </param> /// <param name="contents">The string to write to the file. </param> void WriteAllText(string path, string contents); /// <summary>Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.</summary> /// <param name="path">The file to write to. </param> /// <param name="contents">The string to write to the file. </param> /// <param name="encoding">The encoding to apply to the string.</param> void WriteAllText(string path, string contents, Encoding encoding); /// <summary>Opens a binary file, reads the contents of the file into a byte array, and then closes the file.</summary> /// <returns>A byte array containing the contents of the file.</returns> /// <param name="path">The file to open for reading. </param> byte[] ReadAllBytes(string path); /// <summary>Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.</summary> /// <param name="path">The file to write to. </param> /// <param name="bytes">The bytes to write to the file. </param> void WriteAllBytes(string path, byte[] bytes); /// <summary>Opens a text file, reads all lines of the file, and then closes the file.</summary> /// <returns>A string array containing all lines of the file.</returns> /// <param name="path">The file to open for reading. </param> string[] ReadAllLines(string path); /// <summary>Opens a file, reads all lines of the file with the specified encoding, and then closes the file.</summary> /// <returns>A string array containing all lines of the file.</returns> /// <param name="path">The file to open for reading. </param> /// <param name="encoding">The encoding applied to the contents of the file. </param> string[] ReadAllLines(string path, Encoding encoding); /// <summary>Reads the lines of a file.</summary> /// <returns>All the lines of the file, or the lines that are the result of a query.</returns> /// <param name="path">The file to read.</param> IEnumerable<string> ReadLines(string path); /// <summary>Read the lines of a file that has a specified encoding.</summary> /// <returns>All the lines of the file, or the lines that are the result of a query.</returns> /// <param name="path">The file to read.</param> /// <param name="encoding">The encoding that is applied to the contents of the file. </param> IEnumerable<string> ReadLines(string path, Encoding encoding); /// <summary>Creates a new file, write the specified string array to the file, and then closes the file. </summary> /// <param name="path">The file to write to. </param> /// <param name="contents">The string array to write to the file. </param> void WriteAllLines(string path, string[] contents); /// <summary>Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. </summary> /// <param name="path">The file to write to. </param> /// <param name="contents">The string array to write to the file. </param> /// <param name="encoding">An <see cref="T:System.Text.Encoding" /> object that represents the character encoding applied to the string array.</param> void WriteAllLines(string path, string[] contents, Encoding encoding); /// <summary>Creates a new file, writes a collection of strings to the file, and then closes the file.</summary> /// <param name="path">The file to write to.</param> /// <param name="contents">The lines to write to the file.</param> void WriteAllLines(string path, IEnumerable<string> contents); /// <summary>Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary> /// <param name="path">The file to write to.</param> /// <param name="contents">The lines to write to the file.</param> /// <param name="encoding">The character encoding to use.</param> void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding); /// <summary>Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.</summary> /// <param name="path">The file to append the specified string to. </param> /// <param name="contents">The string to append to the file. </param> void AppendAllText(string path, string contents); /// <summary>Appends the specified string to the file, creating the file if it does not already exist.</summary> /// <param name="path">The file to append the specified string to. </param> /// <param name="contents">The string to append to the file. </param> /// <param name="encoding">The character encoding to use. </param> void AppendAllText(string path, string contents, Encoding encoding); /// <summary>Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.</summary> /// <param name="path">The file to append the lines to. The file is created if it doesn't already exist.</param> /// <param name="contents">The lines to append to the file.</param> void AppendAllLines(string path, IEnumerable<string> contents); /// <summary>Appends lines to a file by using a specified encoding, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.</summary> /// <param name="path">The file to append the lines to. The file is created if it doesn't already exist.</param> /// <param name="contents">The lines to append to the file.</param> /// <param name="encoding">The character encoding to use.</param> void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding); /// <summary>Moves a specified file to a new location, providing the option to specify a new file name.</summary> /// <param name="sourceFileName">The name of the file to move. Can include a relative or absolute path.</param> /// <param name="destFileName">The new path and name for the file.</param> void Move(string sourceFileName, string destFileName); /// <summary>Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.</summary> /// <param name="sourceFileName">The name of a file that replaces the file specified by <paramref name="destinationFileName" />.</param> /// <param name="destinationFileName">The name of the file being replaced.</param> /// <param name="destinationBackupFileName">The name of the backup file.</param> void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); /// <summary>Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors.</summary> /// <param name="sourceFileName">The name of a file that replaces the file specified by <paramref name="destinationFileName" />.</param> /// <param name="destinationFileName">The name of the file being replaced.</param> /// <param name="destinationBackupFileName">The name of the backup file.</param> /// <param name="ignoreMetadataErrors">true to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the replacement file; otherwise, false. </param> void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); } }
using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Mime; using System.Text; using System.Threading; using System.Xml; using System.Collections.Specialized; using System.Collections.Generic; namespace CalbucciLib { /// <summary> /// HTML Parser /// </summary> public class HtmlParser { // ==================================================================== // // STATIC FIELDS // // ==================================================================== private static readonly int _MaxInnerTextLengthStored = 65500; static HashSet<string> _IgnoreTextInsideTag; static char[] _NonSignificantWhitespace; // ==================================================================== // // PRIVATE FIELDS // // ==================================================================== private string _OrigHtml; private bool _Stop; private Action<string, HtmlElement> _TextCallback; private Action<HtmlElement, bool> _ElementCallback; private Action<string> _EndElementCallback; private List<string> _Errors; private List<string> _Warnings; private Dictionary<string, string> _Ids; private StringBuilder _InnerTextBuilder; // ==================================================================== // // CONSTRUCTORS // // ==================================================================== static HtmlParser() { // List of Tags that we will simply drop the TextNode inside them _IgnoreTextInsideTag = new HashSet<string> { "head", "html", "ol", "select", "table", "tbody", "thead", "tfoot", "tr" }; _NonSignificantWhitespace = new char[32]; for (int i = 0; i < 32; i++) _NonSignificantWhitespace[i] = (char)i; } public HtmlParser(string html) { _OrigHtml = html; SkipComments = true; PreserveCRLFTab = true; } // ==================================================================== // // VIRTUAL METHODS (public/protected) // // ==================================================================== // ==================================================================== // // PUBLIC METHODS (instance) // // ==================================================================== /// <summary> /// Parses the HTML /// </summary> /// <param name="textCallback">Call back for text and comments (must set SkipComments to false)</param> /// <param name="elementCallback">Call back for empty elements and open elements</param> /// <param name="endElementCallback">Call back for closing elements</param> /// <returns></returns> public bool Parse(Action<string, HtmlElement> textCallback = null, Action<HtmlElement, bool> elementCallback = null, Action<string> endElementCallback = null) { if (_Stop) { throw new InvalidOperationException("You cannot call parse again."); } _TextCallback = textCallback; _ElementCallback = elementCallback; _EndElementCallback = endElementCallback; HasValidSyntax = true; HasOnlyValidTags = true; HasOnlyValidAttributes = true; HasDeprecatedAttributes = false; HasDeprecatedTags = false; HasOnlyKnownTags = true; _Errors = new List<string>(); _Warnings = new List<string>(); _Ids = new Dictionary<string, string>(); // null html if (_OrigHtml == null) { InnerText = ""; return true; } int itLen = Math.Min(_MaxInnerTextLengthStored, 256 + _OrigHtml.Length / 2); _InnerTextBuilder = new StringBuilder(itLen); // check if this html has at least one tag, otherwise it is just a string int pos = _OrigHtml.IndexOf('<'); if (pos == -1) { CallText(_OrigHtml, null); } else { InternalParse(); } InnerText = WebUtility.HtmlDecode(_InnerTextBuilder.ToString()); _Stop = true; return HasValidSyntax; } /// <summary> /// Stops the parsing. The state of the properties are unknown. /// </summary> public void Stop() { _Stop = true; } // ==================================================================== // // PRIVATE/PROTECTED METHODS // // ==================================================================== private void CallText(string text, HtmlElement parent) { if (PreserveCRLFTab) { if (string.IsNullOrEmpty(text)) return; } if (string.IsNullOrWhiteSpace(text)) return; if (parent != null && parent.ElementInfo != null) { var childrenTypes = parent.ElementInfo.PermittedChildrenTypes; if ((childrenTypes & (HtmlElementType.Text | HtmlElementType.NRCharData)) == 0) { AddWarning(string.Format("Text node inside a {0} element is not valid", parent.TagName)); } } if (parent != null && _IgnoreTextInsideTag.Contains(parent.TagNameNS)) return; bool clearText = !PreserveCRLFTab; if (parent != null) { switch (parent.TagNameNS) { case "pre": case "script": case "style": clearText = false; break; } } if (clearText && text.StartsWith("<!--")) { clearText = false; } if (clearText) { // Remove all tags, CR, LF StringBuilder sb = new StringBuilder(text.Length); int pos = 0; int last = 0; do { pos = text.IndexOfAny(_NonSignificantWhitespace, pos); if (pos == -1) break; if (text[pos] == '\r' || text[pos] == '\n') { sb.Append(text, last, pos - last); sb.Append(' '); } else if (last != pos) { sb.Append(text, last, pos - last); } pos++; last = pos; } while (pos < text.Length); if (last < text.Length) sb.Append(text, last, text.Length - last); text = sb.ToString(); } text = WebUtility.HtmlDecode(text); if (_TextCallback != null) { _TextCallback(text, parent); if (_Stop) return; } bool useBlock = false; if (parent != null && parent.ElementInfo != null) { if (parent.ElementInfo.ElementType == HtmlElementType.Flow) useBlock = true; else { // This is whacky. We messed up on the definition of block-level elements for TR/TD // because of the optional tags. switch (parent.TagNameNS) { case "tr": case "td": useBlock = true; break; } } } if (_InnerTextBuilder.Length < _MaxInnerTextLengthStored) { if (useBlock) { char prevChar = '\0'; if (_InnerTextBuilder.Length > 0) prevChar = _InnerTextBuilder[_InnerTextBuilder.Length - 1]; if (prevChar != '\n' && prevChar != '\r') _InnerTextBuilder.Append("\n"); _InnerTextBuilder.Append(text); _InnerTextBuilder.Append("\n"); } else { _InnerTextBuilder.Append(text); } } } private void InternalParse() { Stack<HtmlElement> openedTags = new Stack<HtmlElement>(); Stack<HtmlElement> openedBlocks = new Stack<HtmlElement>(); bool anyContent = false; HtmlElement parent; HtmlElement blockParent; bool fatal = false; //_LineCount = 1; string text; int last = 0; int len = _OrigHtml.Length; int len1 = len - 1; char c; for (int p = 0; p < len; p++) { if (_Stop) return; c = _OrigHtml[p]; if (c != '<') continue; int diff = p - last; if (diff >= 1) { parent = null; if (HasValidSyntax && openedTags.Count > 0) parent = openedTags.Peek(); string text2 = _OrigHtml.Substring(last, diff); if (!string.IsNullOrWhiteSpace(text2)) anyContent = true; CallText(text2, parent); if (_Stop) return; } // Yes, this is an open (or closing) tag if (p >= len1) { HasValidSyntax = false; fatal = true; AddError("HTML ends with < character"); break; // the html ends with this open tag } int startElem = p; string elem = GetElementString(startElem); if (elem == null) { fatal = true; break; // fatal syntax error } p += elem.Length - 1; if (elem.Length <= 2) { // bad HTML, like "<>" AddError("Element is empty <>"); HasValidSyntax = false; continue; } last = p + 1; parent = blockParent = null; if (HasValidSyntax) { if (openedTags.Count > 0) parent = openedTags.Peek(); if (openedBlocks.Count > 0) blockParent = openedBlocks.Peek(); } if (elem[1] == '/') { anyContent = true; // This is a closing tag string tag = HtmlElement.ParseClosingTag(elem); if (HasValidSyntax) { UnwindForClose(tag, openedTags, openedBlocks); if (_Stop) return; } if (_EndElementCallback != null) { _EndElementCallback(tag); if (_Stop) return; } } else { if (elem.StartsWith("<!")) { if (elem.StartsWith("<!--")) { p = p - elem.Length + 1; // It's a comment int ec = _OrigHtml.IndexOf("-->", p + 4, StringComparison.InvariantCultureIgnoreCase); if (ec == -1) { HasValidSyntax = false; fatal = true; AddError("Missing end comment -->"); break; } text = _OrigHtml.Substring(p, ec - p + 3); if (!SkipComments) { CallText(text, null); if (_Stop) return; } p += text.Length; last = p; p--; continue; } // Looks like a doctype string e2 = elem.ToLower(); if (e2.StartsWith("<!doctype ")) { if (anyContent) { HasValidSyntax = false; AddError("The doctype declaration must be the first element of the HTML:" + e2); } anyContent = true; CallText(elem, null); if (_Stop) return; continue; } } anyContent = true; HtmlElement he = new HtmlElement(elem, parent, _Errors, _Warnings); if (he.HasDeprecatedAttribute) HasDeprecatedAttributes = true; if (!he.HasOnlyKnownAttributes) HasOnlyValidAttributes = false; if (!string.IsNullOrWhiteSpace(he.Id)) { if (_Ids.ContainsKey(he.Id)) { AddWarning("Duplicate id: " + he.Id + " - Element: " + he.OriginalOpenTag); } _Ids[he.Id] = he.Id; } if (he.SyntaxError) { HasValidSyntax = false; if (he.FatalSyntaxError) { fatal = true; break; } AddError("Element syntax error for " + he.OriginalOpenTag); continue; } // Special cases for script and style if (he.TagNameNS == "script" || he.TagNameNS == "style") { int startScript = p + 1; int endScript = 0; string endTag = null; int cp = startScript; while (true) { cp = _OrigHtml.IndexOf("</", cp, StringComparison.InvariantCultureIgnoreCase); if (cp == -1) { HasValidSyntax = false; fatal = true; AddError("Missing close tag: " + he.OriginalOpenTag); break; } endScript = cp; elem = GetElementString(cp); if (elem == null) { HasValidSyntax = false; fatal = true; AddError("Missing close > for closing tag: " + he.OriginalOpenTag); break; } cp += elem.Length; last = cp; endTag = HtmlElement.ParseClosingTag(elem); if (endTag == he.TagNameNS) break; endTag = null; } if (endTag == null) { p = _OrigHtml.Length; break; } p = cp - 1; if (_ElementCallback != null) { _ElementCallback(he, false); if (_Stop) return; } CallText(_OrigHtml.Substring(startScript, endScript - startScript), he); if (_Stop) return; if (_EndElementCallback != null) { _EndElementCallback(he.TagNameNS); if (_Stop) return; } continue; } // We consider this a single element if // 1) the ElementInfo.Single is flagged // 2) It is an unknown element (but not in any namespace) if (he.ElementInfo == null) { HasOnlyKnownTags = false; // Unknown HTML 4.01 tag if (!he.HasNamespace) { AddWarning("Unknown tag: " + he.TagNameNS); // Really unknown and invalid tag if (he.XmlEmptyTag) { if (_ElementCallback != null) { _ElementCallback(he, true); if (_Stop) return; } } else { if (_ElementCallback != null) { _ElementCallback(he, false); if (_Stop) return; } if (HasValidSyntax) openedTags.Push(he); } } else { // it is unknown, but correctly declared in an XML namespace if (he.XmlEmptyTag) { if (_ElementCallback != null) { _ElementCallback(he, true); if (_Stop) return; } } else { if (_ElementCallback != null) { _ElementCallback(he, false); if (_Stop) return; } if (HasValidSyntax) openedTags.Push(he); } } } else { if (he.ElementInfo.Obsolete) { AddWarning("Deprecated Tag: " + he.TagNameNS); HasDeprecatedTags = true; } // It's known tag if (he.ElementInfo.TagFormatting == HtmlTagFormatting.Single || he.XmlEmptyTag) { if (_ElementCallback != null) { _ElementCallback(he, true); if (_Stop) return; } } else { if (HasValidSyntax) { if (he.ElementInfo.ElementType == HtmlElementType.Flow) { // Some Tags have optional closing (like LI or TD or P) // We assume an automatic closing for these tags on the following situation: // 1) Current element is block-level, and // 2) Parent node is also a block-level and supports optional closing // 3) Current element is the same class as parent element // or Current element is the closing tag of the parent element if (blockParent != null && blockParent.ElementInfo.TagFormatting == HtmlTagFormatting.OptionalClosing) { if (!Equals(parent, blockParent)) { AddWarning(string.Format("Invalid parent for {0} (inside of {1})", blockParent.TagName, parent.TagName)); } else { if (he.TagName == blockParent.TagName) { if (_EndElementCallback != null) { _EndElementCallback(parent.TagNameNS); if (_Stop) return; } openedTags.Pop(); openedBlocks.Pop(); } } } if (HasValidSyntax) openedBlocks.Push(he); } if (HasValidSyntax) openedTags.Push(he); } if (_ElementCallback != null) _ElementCallback(he, false); } } } } // for loop if (!fatal) { // commit the last piece of text parent = null; if (HasValidSyntax && openedTags.Count > 0) parent = openedTags.Peek(); if (last < len) { text = _OrigHtml.Substring(last); CallText(text, parent); if (_Stop) return; } if (HasValidSyntax) { while (openedTags.Count > 0) { parent = openedTags.Peek(); if (parent.ElementInfo == null || parent.ElementInfo.TagFormatting != HtmlTagFormatting.OptionalClosing) break; if (_EndElementCallback != null) { _EndElementCallback(parent.TagNameNS); if (_Stop) return; } openedTags.Pop(); blockParent = null; if (openedBlocks.Count > 0) blockParent = openedBlocks.Peek(); if (Equals(parent, blockParent)) openedBlocks.Pop(); } } } if (HasValidSyntax) { if (openedBlocks.Count > 0) { if (openedTags.Count != openedBlocks.Count) { HasValidSyntax = false; AddError("Missing " + openedTags.Count + " tag(s) closing."); } else { while (openedBlocks.Count > 0) { blockParent = openedBlocks.Pop(); parent = openedTags.Pop(); if (!Equals(parent, blockParent)) { HasValidSyntax = false; AddError("Missing a close tag for a block-element. Opened Tag: " + parent.TagNameNS); break; } if (_EndElementCallback != null) { _EndElementCallback(parent.TagNameNS); if (_Stop) return; } } } } else if (openedTags.Count > 0) { AddError("Missing " + openedTags.Count + " tag(s) closing."); HasValidSyntax = false; } } } private void UnwindForClose(string tag, Stack<HtmlElement> openedTags, Stack<HtmlElement> openedBlocks) { HtmlElement parent = null; if (openedTags.Count > 0) parent = openedTags.Peek(); if (parent == null) { HasValidSyntax = false; AddError("Closing tag without opening: " + tag); return; } string firstParent = parent.TagNameNS; HtmlElement blockParent = null; if (openedBlocks.Count > 0) blockParent = openedBlocks.Peek(); do { if (parent.TagNameNS == tag) { openedTags.Pop(); if (blockParent != null && blockParent.TagNameNS == tag) openedBlocks.Pop(); return; } if (parent.ElementInfo == null) break; // mismatch // This could be either a tag mismatch, or an optional element missing if (parent.ElementInfo.TagFormatting != HtmlTagFormatting.OptionalClosing) break; // mismatch // inject the optional closing tag if (_EndElementCallback != null) { _EndElementCallback(parent.TagNameNS); if (_Stop) return; } if (openedTags.Count == 0) break; openedTags.Pop(); if (Equals(blockParent, parent)) { openedBlocks.Pop(); blockParent = null; if (openedBlocks.Count > 0) blockParent = openedBlocks.Peek(); } parent = parent.Parent; } while (parent != null); AddError("Tag mismatch. Open tag: " + firstParent + " / Closing tag: " + tag); HasValidSyntax = false; } // ==================================================================== // // STATIC METHODS (public) // // ==================================================================== // ==================================================================== // // STATIC METHODS (private/protected) // // ==================================================================== private string GetElementString(int startPos) { char c; int endElem = 0; int len = _OrigHtml.Length; int p = startPos; for (; p < len; p++) { c = _OrigHtml[p]; if (c == '>') { endElem = p; break; } if (c == '\"' || c == '\'') { p = _OrigHtml.IndexOf(c, p + 1); if (p == -1) { // Not well formed HTML: <div attr="value> (missing quote) var logString = _OrigHtml.Substring(startPos); if (logString.Length > 40) logString = logString.Substring(40); AddError("Attribute start quote but doesn't end with quote: " + logString); HasValidSyntax = false; return null; } } } if (endElem == 0) { HasValidSyntax = false; var logString = _OrigHtml.Substring(startPos); if (logString.Length > 40) logString = logString.Substring(40); AddError("Can't find > for tag: " + logString); return null; } return _OrigHtml.Substring(startPos, endElem - startPos + 1); } private void AddError(string error) { _Errors.Add(error); } private void AddWarning(string warning) { _Warnings.Add(warning); } // ==================================================================== // // PROPERTIES // // ==================================================================== public string InnerText { get; private set; } /// <summary> /// /// </summary> public bool IsValidStrictHTML401 { get { return HasValidSyntax && HasOnlyValidTags && HasOnlyValidAttributes; } } public bool IsValidStrictHTMLNoDeprecated { get { return HasValidSyntax && HasOnlyValidTags && HasOnlyValidAttributes && !HasDeprecatedAttributes && !HasDeprecatedTags; } } public bool IsValidHTML401 { get { return HasValidSyntax && HasOnlyValidTags && HasOnlyValidAttributes; } } /// <summary> /// The document is syntatically correct /// </summary> public bool HasValidSyntax { get; private set; } /// <summary> /// All tags on the document are valid HTML 4.01 tags (known or declared using namespaces) /// </summary> public bool HasOnlyValidTags { get; private set; } /// <summary> /// All attributes on the document are defined in HTML 4.01 (we don't validate the value of the attributes) /// </summary> public bool HasOnlyValidAttributes { get; private set; } public bool HasOnlyKnownTags { get; private set; } public bool HasDeprecatedAttributes { get; private set; } /// <summary> /// Has at least one tag or one attribute that is deprecated /// </summary> public bool HasDeprecatedTags { get; private set; } public List<string> Errors { get { return _Errors; } } public List<string> Warnings { get { return _Warnings; } } public bool SkipComments { get; set; } public bool PreserveCRLFTab { get; set; } // ==================================================================== // // INTERFACE IMPLEMENTATIONS // // ==================================================================== } }
using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; namespace PHP.Testing { /// <summary> /// Summary description for Class1. /// </summary> class PhpNetTester { private static TestsCollection testsCollection; private static readonly List<string> testDirsAndFiles = new List<string>(); private static string outputDir; private static string compiler; private static string loader; private static string php; private static bool fullLog = false; private static bool verbose = false; private static bool clean = false; private static bool compileOnly = false; private static bool benchmarks = false; private static int numberOfBenchmarkRuns = 1; private static int maxThreads = 1; private static TestsCollection.ConcurrencyLevel concurrencyLevel = TestsCollection.ConcurrencyLevel.SkipIf; public static int BenchmarkWarmup { get { return benchmarkWarmup; } } private static int benchmarkWarmup = 1; #region Command Line private static void ShowHelp() { Console.WriteLine("Usage:"); Console.WriteLine(" /compiler:<absolute or relative path to Phalanger (phpc.exe)>"); Console.WriteLine(" - set to phpc.exe in current directory if not specified"); Console.WriteLine(" /php:<absolute or relative path to PHP executable file>"); Console.WriteLine(" - set to php.exe in current directory if not specified"); Console.WriteLine(" /loader:<absolute or relative path to a .NET executable loader>"); Console.WriteLine(" - useful for testing on Mono (loader = mono.exe)"); Console.WriteLine(" - .NET executables are run directly if the option is not specified"); Console.WriteLine(" /log:full|short"); Console.WriteLine(" - default is short"); Console.WriteLine(" /out:<absolute or relative path to directory where should be log created>"); Console.WriteLine(" - default is current directory"); Console.WriteLine(" /verbose - writes much more information to console while testing"); Console.WriteLine(" /clean - deletes all files created during the test"); Console.WriteLine(" /compileonly - test only compilation, do not run compiled scripts"); Console.WriteLine(" /benchmark:<runs>[/<warmup>] - run benchmarks"); Console.WriteLine(" /j[:max-threads] - execute in parallel (may affect benchmarks)"); Console.WriteLine(" /p:<none|folder|compile|skipif|full> - concurrency level:"); Console.WriteLine(" none - Everything sequential. Disables /j option."); Console.WriteLine(" folder - Tests in separate folders executed concurrently."); Console.WriteLine(" compile - Only compiled concurrently in same folder."); Console.WriteLine(" skipif - SkipIf tests executed concurrently in same folder."); Console.WriteLine(" full - All possible operations done concurrently."); Console.WriteLine(" arguments <absolute or relative directory paths where are directories to test>"); Console.WriteLine(" or <absolute or relative paths to test files>"); Console.WriteLine(" - current directory if no argument is specified"); } /// <summary> /// Processes command line arguments. /// </summary> /// <param name="args">The command line arguments.</param> /// <returns>Whether to run compilation.</returns> private static bool ProcessArguments(string[] args) { for (int i = 0; i < args.Length; i++) { Debug.Assert(args[i].Length > 0); // option: if (args[i][0] == '/') { int colon = args[i].IndexOf(':'); if (colon >= 0) { // option having format "/name:value" string name = args[i].Substring(1, colon - 1).Trim(); string value = args[i].Substring(colon + 1).Trim(); switch (name) { case "compiler": if (compiler != null) throw new InvalidArgumentException(String.Format("Option {0} specified twice.", name)); compiler = Path.GetFullPath(value); if (!File.Exists(compiler)) throw new InvalidArgumentException(String.Format("Compiler {0} not found.", compiler)); break; case "loader": if (loader != null) throw new InvalidArgumentException(String.Format("Option {0} specified twice.", name)); loader = Path.GetFullPath(value); if (!File.Exists(loader)) throw new InvalidArgumentException(String.Format("Compiler {0} not found.", loader)); break; case "out": if (outputDir != null) throw new InvalidArgumentException(String.Format("Option {0} specified twice.", name)); outputDir = Path.GetFullPath(value); if (!Directory.Exists(outputDir)) throw new InvalidArgumentException(String.Format("Output directory {0} not found.", outputDir)); break; case "php": if (php != null) throw new InvalidArgumentException(String.Format("Option {0} specified twice.", name)); php = Path.GetFullPath(value); if (!File.Exists(php)) throw new InvalidArgumentException(String.Format("PHP (original) executable file {0} not found.", php)); break; case "log": if (value == "full") fullLog = true; else if (value == "short") fullLog = false; else throw new InvalidArgumentException(String.Format("Illegal /log:{0} option.", value)); break; case "benchmark": if (benchmarks) { throw new InvalidArgumentException("/benchmark option specified twice"); } benchmarks = true; try { int slash = value.IndexOf('/'); if (slash < 0) { numberOfBenchmarkRuns = Int32.Parse(value); } else { numberOfBenchmarkRuns = Int32.Parse(value.Substring(0, slash)); benchmarkWarmup = Int32.Parse(value.Substring(slash + 1)); } } catch (Exception) { throw new TestException("Error /benchmark value."); } break; case "j": maxThreads = Math.Max(Int32.Parse(value), 1); break; case "p": switch (value) { case "none": maxThreads = 1; concurrencyLevel = TestsCollection.ConcurrencyLevel.None; break; case "folder": concurrencyLevel = TestsCollection.ConcurrencyLevel.Folder; break; case "compile": concurrencyLevel = TestsCollection.ConcurrencyLevel.Compile; break; case "skipif": concurrencyLevel = TestsCollection.ConcurrencyLevel.SkipIf; break; case "full": concurrencyLevel = TestsCollection.ConcurrencyLevel.Full; break; default: throw new InvalidArgumentException( String.Format( "Invalid value for conncurrency-level [{0}] in option [{1}].", value, name)); } break; default: throw new InvalidArgumentException(String.Format("Invalid option {0}.", name)); } } else { // option without ':' string name = args[i].Substring(1).Trim(); switch (name) { case "verbose": verbose = true; break; case "clean": clean = true; break; case "compileonly": compileOnly = true; break; case "j": maxThreads = Environment.ProcessorCount; break; default: throw new InvalidArgumentException(String.Format("Invalid option {0}.", args[i])); } } } else { // arguments testDirsAndFiles.Add(args[i]); } } if (maxThreads <= 1) { concurrencyLevel = TestsCollection.ConcurrencyLevel.None; } else if (concurrencyLevel == TestsCollection.ConcurrencyLevel.None) { maxThreads = 1; } // default values if (testDirsAndFiles.Count == 0) { testDirsAndFiles.Add(Directory.GetCurrentDirectory()); } if (compiler == null) { compiler = Path.Combine(Directory.GetCurrentDirectory(), "phpc.exe"); } if (php == null) { php = Path.Combine(Directory.GetCurrentDirectory(), "php.exe"); } if (outputDir == null) { outputDir = Directory.GetCurrentDirectory(); } return true; } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static int Main(string[] args) { var sw = Stopwatch.StartNew(); bool testingStarted = false; Console.WriteLine("Starting tests..."); try { ProcessArguments(args); testsCollection = new TestsCollection(testDirsAndFiles, verbose, clean, compileOnly, benchmarks, numberOfBenchmarkRuns, concurrencyLevel, maxThreads); testsCollection.LoadTests(); testingStarted = true; return testsCollection.RunTests(loader, compiler, php); } catch (InvalidArgumentException e) { Console.WriteLine(e.Message); ShowHelp(); Console.ReadLine(); } catch (TestException e) { Console.WriteLine("Testing failed: " + e.Message); Console.ReadLine(); } catch (Exception e) { Console.Write("Unexpected error: "); Console.WriteLine(e.Message); Console.ReadLine(); } finally { if (testingStarted) { testsCollection.WriteLog(Path.Combine(outputDir, "TestLog.htm"), fullLog); Console.WriteLine(); Console.WriteLine("Done. " + testsCollection.GetStatusMessage()); Console.WriteLine("Time: " + sw.Elapsed); } } return 0; } } }
// 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.Linq; using System.Reflection; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class AnalyzerHelper { private const string CSharpCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.CSharp.CSharpCompilerDiagnosticAnalyzer"; private const string VisualBasicCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.VisualBasic.VisualBasicCompilerDiagnosticAnalyzer"; // These are the error codes of the compiler warnings. // Keep the ids the same so that de-duplication against compiler errors // works in the error list (after a build). internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032"; internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376"; internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033"; internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377"; internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034"; internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378"; // Shared with Compiler internal const string AnalyzerExceptionDiagnosticId = "AD0001"; internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002"; // IDE only errors internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000"; internal const string WRN_NoAnalyzerInAssemblyId = "AD1001"; internal const string WRN_UnableToLoadAnalyzerId = "AD1002"; private const string AnalyzerExceptionDiagnosticCategory = "Intellisense"; public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer) { return analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer; } public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer) { return analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer(); } public static bool IsOpenFileOnly(this DiagnosticAnalyzer analyzer, Workspace workspace) { var builtInAnalyzer = analyzer as IBuiltInAnalyzer; if (builtInAnalyzer != null) { return builtInAnalyzer.OpenFileOnly(workspace); } return false; } public static bool HasNonHiddenDescriptor(this DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, Project project) { // most of analyzers, number of descriptor is quite small, so this should be cheap. return service.GetDiagnosticDescriptors(analyzer).Any(d => d.GetEffectiveSeverity(project.CompilationOptions) != ReportDiagnostic.Hidden); } public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? descriptor.DefaultSeverity.MapSeverityToReport() : descriptor.GetEffectiveSeverity(options); } public static ReportDiagnostic MapSeverityToReport(this DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.UnexpectedValue(severity); } } public static bool IsCompilerAnalyzer(this DiagnosticAnalyzer analyzer) { // TODO: find better way. var typeString = analyzer.GetType().ToString(); if (typeString == CSharpCompilerAnalyzerTypeName) { return true; } if (typeString == VisualBasicCompilerAnalyzerTypeName) { return true; } return false; } public static ValueTuple<string, VersionStamp> GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer) { // Get the unique ID for given diagnostic analyzer. // note that we also put version stamp so that we can detect changed analyzer. var typeInfo = analyzer.GetType().GetTypeInfo(); return ValueTuple.Create(analyzer.GetAnalyzerId(), GetAnalyzerVersion(CorLightup.Desktop.GetAssemblyLocation(typeInfo.Assembly))); } public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer) { var typeInfo = analyzer.GetType().GetTypeInfo(); return typeInfo.Assembly.GetName().Name; } public static Task<OptionSet> GetDocumentOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var workspaceAnalyzerOptions = analyzerOptions as WorkspaceAnalyzerOptions; if (workspaceAnalyzerOptions == null) { return SpecializedTasks.Default<OptionSet>(); } return workspaceAnalyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken); } internal static void OnAnalyzerException_NoTelemetryLogging( Exception ex, DiagnosticAnalyzer analyzer, Diagnostic diagnostic, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource, ProjectId projectIdOpt) { if (diagnostic != null) { hostDiagnosticUpdateSource?.ReportAnalyzerDiagnostic(analyzer, diagnostic, hostDiagnosticUpdateSource?.Workspace, projectIdOpt); } if (IsBuiltInAnalyzer(analyzer)) { FatalError.ReportWithoutCrashUnlessCanceled(ex); } } internal static void OnAnalyzerExceptionForSupportedDiagnostics(DiagnosticAnalyzer analyzer, Exception exception, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) { if (exception is OperationCanceledException) { return; } var diagnostic = CreateAnalyzerExceptionDiagnostic(analyzer, exception); OnAnalyzerException_NoTelemetryLogging(exception, analyzer, diagnostic, hostDiagnosticUpdateSource, projectIdOpt: null); } /// <summary> /// Create a diagnostic for exception thrown by the given analyzer. /// </summary> /// <remarks> /// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic". /// </remarks> internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e) { var analyzerName = analyzer.ToString(); // TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance. // However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field. // This requires us to create a new DiagnosticDescriptor instance per diagnostic instance. var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId, title: FeaturesResources.User_Diagnostic_Analyzer_Failure, messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2, description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()), category: AnalyzerExceptionDiagnosticCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message); } private static VersionStamp GetAnalyzerVersion(string path) { if (path == null || !File.Exists(path)) { return VersionStamp.Default; } return VersionStamp.Create(File.GetLastWriteTimeUtc(path)); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(string fullPath, AnalyzerLoadFailureEventArgs e) { return CreateAnalyzerLoadFailureDiagnostic(null, null, null, fullPath, e); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic( Workspace workspace, ProjectId projectId, string language, string fullPath, AnalyzerLoadFailureEventArgs e) { if (!TryGetErrorMessage(language, fullPath, e, out var id, out var message, out var messageFormat, out var description)) { return null; } return new DiagnosticData( id, FeaturesResources.Roslyn_HostError, message, messageFormat, severity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description, warningLevel: 0, workspace: workspace, projectId: projectId); } private static bool TryGetErrorMessage( string language, string fullPath, AnalyzerLoadFailureEventArgs e, out string id, out string message, out string messageFormat, out string description) { switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: id = Choose(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB); messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1; message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: id = Choose(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB); messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2; message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: id = Choose(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB); messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers; message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.None: default: id = string.Empty; message = string.Empty; messageFormat = string.Empty; description = string.Empty; return false; } return true; } private static string Choose(string language, string noLanguageMessage, string csharpMessage, string vbMessage) { if (language == null) { return noLanguageMessage; } return language == LanguageNames.CSharp ? csharpMessage : vbMessage; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // The System.Net.Sockets.TcpClient class provide TCP services at a higher level // of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient // is used to create a Client connection to a remote host. public class TcpClient : IDisposable { private Socket _clientSocket; private bool _active; private NetworkStream _dataStream; // IPv6: Maintain address family for the client. private AddressFamily _family = AddressFamily.InterNetwork; // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient() : this(AddressFamily.InterNetwork) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", null); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient(AddressFamily family) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", family); } // Validate parameter if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), "family"); } _family = family; initialize(); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by TcpListener.Accept(). internal TcpClient(Socket acceptedSocket) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", acceptedSocket); } Client = acceptedSocket; _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by the class to provide the underlying network socket. public Socket Client { get { return _clientSocket; } set { _clientSocket = value; } } // Used by the class to indicate that a connection has been made. protected bool Active { get { return _active; } set { _active = value; } } public int Available { get { return _clientSocket.Available; } } public bool Connected { get { return _clientSocket.Connected; } } public bool ExclusiveAddressUse { get { return _clientSocket.ExclusiveAddressUse; } set { _clientSocket.ExclusiveAddressUse = value; } } internal IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", host); } IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", address); } IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", addresses); } IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal void EndConnect(IAsyncResult asyncResult) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "EndConnect", asyncResult); } Client.EndConnect(asyncResult); _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "EndConnect", null); } } public Task ConnectAsync(IPAddress address, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, address, port, null); } public Task ConnectAsync(string host, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, host, port, null); } public Task ConnectAsync(IPAddress[] addresses, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, addresses, port, null); } // Returns the stream used to read and write data to the remote host. public NetworkStream GetStream() { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "GetStream", ""); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!Client.Connected) { throw new InvalidOperationException(SR.net_notconnected); } if (_dataStream == null) { _dataStream = new NetworkStream(Client, true); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "GetStream", _dataStream); } return _dataStream; } private bool _cleanedUp = false; // Disposes the Tcp connection. protected virtual void Dispose(bool disposing) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Dispose", ""); } if (_cleanedUp) { if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } return; } if (disposing) { IDisposable dataStream = _dataStream; if (dataStream != null) { dataStream.Dispose(); } else { // If the NetworkStream wasn't created, the Socket might // still be there and needs to be closed. In the case in which // we are bound to a local IPEndPoint this will remove the // binding and free up the IPEndPoint for later uses. Socket chkClientSocket = Client; if (chkClientSocket != null) { try { chkClientSocket.InternalShutdown(SocketShutdown.Both); } finally { chkClientSocket.Dispose(); Client = null; } } } GC.SuppressFinalize(this); } _cleanedUp = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } } public void Dispose() { Dispose(true); } ~TcpClient() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) { #endif Dispose(false); #if DEBUG } #endif } // Gets or sets the size of the receive buffer in bytes. public int ReceiveBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } } // Gets or sets the size of the send buffer in bytes. public int SendBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } } // Gets or sets the receive time out value of the connection in seconds. public int ReceiveTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } // Gets or sets the send time out value of the connection in seconds. public int SendTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } // Gets or sets the value of the connection's linger option. public LingerOption LingerState { get { return (LingerOption)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value); } } // Enables or disables delay when send or receive buffers are full. public bool NoDelay { get { return numericOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false; } set { Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0); } } private void initialize() { // IPv6: Use the address family from the constructor (or Connect method). Client = new Socket(_family, SocketType.Stream, ProtocolType.Tcp); _active = false; } private int numericOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { return (int)Client.GetSocketOption(optionLevel, optionName); } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; namespace System.Linq.Expressions.Compiler { internal partial class StackSpiller { private class TempMaker { /// <summary> /// Current temporary variable /// </summary> private int _temp; /// <summary> /// List of free temporary variables. These can be recycled for new temps. /// </summary> private List<ParameterExpression> _freeTemps; /// <summary> /// Stack of currently active temporary variables. /// </summary> private Stack<ParameterExpression> _usedTemps; /// <summary> /// List of all temps created by stackspiller for this rule/lambda /// </summary> private List<ParameterExpression> _temps = new List<ParameterExpression>(); internal List<ParameterExpression> Temps { get { return _temps; } } internal ParameterExpression Temp(Type type) { ParameterExpression temp; if (_freeTemps != null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) { temp = _freeTemps[i]; if (temp.Type == type) { _freeTemps.RemoveAt(i); return UseTemp(temp); } } } // Not on the free-list, create a brand new one. temp = Expression.Variable(type, "$temp$" + _temp++); _temps.Add(temp); return UseTemp(temp); } private ParameterExpression UseTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); if (_usedTemps == null) { _usedTemps = new Stack<ParameterExpression>(); } _usedTemps.Push(temp); return temp; } private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); if (_freeTemps == null) { _freeTemps = new List<ParameterExpression>(); } _freeTemps.Add(temp); } internal int Mark() { return _usedTemps != null ? _usedTemps.Count : 0; } // Free temporaries created since the last marking. // This is a performance optimization to lower the overall number of tempories needed. internal void Free(int mark) { // (_usedTemps != null) ==> (mark <= _usedTemps.Count) Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); // (_usedTemps == null) ==> (mark == 0) Debug.Assert(mark == 0 || _usedTemps != null); if (_usedTemps != null) { while (mark < _usedTemps.Count) { FreeTemp(_usedTemps.Pop()); } } } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void VerifyTemps() { Debug.Assert(_usedTemps == null || _usedTemps.Count == 0); } } /// <summary> /// Rewrites child expressions, spilling them into temps if needed. The /// stack starts in the inital state, and after the first subexpression /// is added it is change to non-empty. This behavior can be overridden /// by setting the stack manually between adds. /// /// When all children have been added, the caller should rewrite the /// node if Rewrite is true. Then, it should call Finish with either /// the original expression or the rewritten expression. Finish will call /// Expression.Comma if necessary and return a new Result. /// </summary> private class ChildRewriter { private readonly StackSpiller _self; private readonly Expression[] _expressions; private int _expressionsCount; private List<Expression> _comma; private RewriteAction _action; private Stack _stack; private bool _done; internal ChildRewriter(StackSpiller self, Stack stack, int count) { _self = self; _stack = stack; _expressions = new Expression[count]; } internal void Add(Expression node) { Debug.Assert(!_done); if (node == null) { _expressions[_expressionsCount++] = null; return; } Result exp = _self.RewriteExpression(node, _stack); _action |= exp.Action; _stack = Stack.NonEmpty; // track items in case we need to copy or spill stack _expressions[_expressionsCount++] = exp.Node; } internal void Add(IList<Expression> expressions) { for (int i = 0, count = expressions.Count; i < count; i++) { Add(expressions[i]); } } internal void AddArguments(IArgumentProvider expressions) { for (int i = 0, count = expressions.ArgumentCount; i < count; i++) { Add(expressions.GetArgument(i)); } } private void EnsureDone() { // done adding arguments, build the comma if necessary if (!_done) { _done = true; if (_action == RewriteAction.SpillStack) { Expression[] clone = _expressions; int count = clone.Length; List<Expression> comma = new List<Expression>(count + 1); for (int i = 0; i < count; i++) { if (clone[i] != null) { Expression temp; clone[i] = _self.ToTemp(clone[i], out temp); comma.Add(temp); } } comma.Capacity = comma.Count + 1; _comma = comma; } } } internal bool Rewrite { get { return _action != RewriteAction.None; } } internal RewriteAction Action { get { return _action; } } internal Result Finish(Expression expr) { EnsureDone(); if (_action == RewriteAction.SpillStack) { Debug.Assert(_comma.Capacity == _comma.Count + 1); _comma.Add(expr); expr = MakeBlock(_comma); } return new Result(_action, expr); } internal Expression this[int index] { get { EnsureDone(); if (index < 0) { index += _expressions.Length; } return _expressions[index]; } } internal Expression[] this[int first, int last] { get { EnsureDone(); if (last < 0) { last += _expressions.Length; } int count = last - first + 1; ContractUtils.RequiresArrayRange(_expressions, first, count, nameof(first), nameof(last)); if (count == _expressions.Length) { Debug.Assert(first == 0); // if the entire array is requested just return it so we don't make a new array return _expressions; } Expression[] clone = new Expression[count]; Array.Copy(_expressions, first, clone, 0, count); return clone; } } } private ParameterExpression MakeTemp(Type type) { return _tm.Temp(type); } private int Mark() { return _tm.Mark(); } private void Free(int mark) { _tm.Free(mark); } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private void VerifyTemps() { _tm.VerifyTemps(); } /// <summary> /// Will perform: /// save: temp = expression /// return value: temp /// </summary> private ParameterExpression ToTemp(Expression expression, out Expression save) { ParameterExpression temp = MakeTemp(expression.Type); save = Expression.Assign(temp, expression); return temp; } /// <summary> /// Creates a special block that is marked as not allowing jumps in. /// This should not be used for rewriting BlockExpression itself, or /// anything else that supports jumping. /// </summary> private static Expression MakeBlock(params Expression[] expressions) { return MakeBlock((IList<Expression>)expressions); } /// <summary> /// Creates a special block that is marked as not allowing jumps in. /// This should not be used for rewriting BlockExpression itself, or /// anything else that supports jumping. /// </summary> private static Expression MakeBlock(IList<Expression> expressions) { return new SpilledExpressionBlock(expressions); } } /// <summary> /// A special subtype of BlockExpression that indicates to the compiler /// that this block is a spilled expression and should not allow jumps in. /// </summary> internal sealed class SpilledExpressionBlock : BlockN { internal SpilledExpressionBlock(IList<Expression> expressions) : base(expressions) { } [ExcludeFromCodeCoverage] // Unreachable internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// Container for the parameters to the RegisterWorkflowType operation. /// <para> Registers a new <i>workflow type</i> and its configuration settings in the specified domain. </para> <para> The retention period for /// the workflow history is set by the RegisterDomain action. </para> <para><b>IMPORTANT:</b> If the type already exists, then a /// TypeAlreadyExists fault is returned. You cannot change the configuration settings of a workflow type once it is registered and it must be /// registered as a new version. </para> <para> <b>Access Control</b> </para> <para>You can use IAM policies to control this action's access to /// Amazon SWF resources as follows:</para> /// <ul> /// <li>Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.</li> /// <li>Use an <c>Action</c> element to allow or deny permission to call this action.</li> /// <li>Constrain the following parameters by using a <c>Condition</c> element with the appropriate keys. /// <ul> /// <li> <c>defaultTaskList</c> : String constraint. The key is <c>swf:defaultTaskList.name</c> .</li> /// <li> <c>name</c> : String constraint. The key is <c>swf:name</c> .</li> /// <li> <c>version</c> : String constraint. The key is <c>swf:version</c> .</li> /// /// </ul> /// </li> /// /// </ul> /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see Using IAM to Manage /// Access to Amazon SWF Workflows.</para> /// </summary> /// <seealso cref="Amazon.SimpleWorkflow.AmazonSimpleWorkflow.RegisterWorkflowType"/> public class RegisterWorkflowTypeRequest : AmazonWebServiceRequest { private string domain; private string name; private string version; private string description; private string defaultTaskStartToCloseTimeout; private string defaultExecutionStartToCloseTimeout; private TaskList defaultTaskList; private string defaultChildPolicy; /// <summary> /// The name of the domain in which to register the workflow type. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Domain { get { return this.domain; } set { this.domain = value; } } /// <summary> /// Sets the Domain property /// </summary> /// <param name="domain">The value to set for the Domain property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDomain(string domain) { this.domain = domain; return this; } // Check to see if Domain property is set internal bool IsSetDomain() { return this.domain != null; } /// <summary> /// The name of the workflow type. The specified string must not start or end with whitespace. It must not contain a <c>:</c> (colon), <c>/</c> /// (slash), <c>|</c> (vertical bar), or any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal string /// "arn". /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// The version of the workflow type. <note> The workflow type consists of the name and version, the combination of which must be unique within /// the domain. To get a list of all currently registered workflow types, use the <a>ListWorkflowTypes</a> action. </note> The specified string /// must not start or end with whitespace. It must not contain a <c>:</c> (colon), <c>/</c> (slash), <c>|</c> (vertical bar), or any control /// characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal string "arn". /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 64</description> /// </item> /// </list> /// </para> /// </summary> public string Version { get { return this.version; } set { this.version = value; } } /// <summary> /// Sets the Version property /// </summary> /// <param name="version">The value to set for the Version property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithVersion(string version) { this.version = version; return this; } // Check to see if Version property is set internal bool IsSetVersion() { return this.version != null; } /// <summary> /// Textual description of the workflow type. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 1024</description> /// </item> /// </list> /// </para> /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// If set, specifies the default maximum duration of decision tasks for this workflow type. This default can be overridden when starting a /// workflow execution using the <a>StartWorkflowExecution</a> action or the <c>StartChildWorkflowExecution</c> <a>Decision</a>. The valid /// values are integers greater than or equal to <c>0</c>. An integer value can be used to specify the duration in seconds while <c>NONE</c> can /// be used to specify unlimited duration. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string DefaultTaskStartToCloseTimeout { get { return this.defaultTaskStartToCloseTimeout; } set { this.defaultTaskStartToCloseTimeout = value; } } /// <summary> /// Sets the DefaultTaskStartToCloseTimeout property /// </summary> /// <param name="defaultTaskStartToCloseTimeout">The value to set for the DefaultTaskStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDefaultTaskStartToCloseTimeout(string defaultTaskStartToCloseTimeout) { this.defaultTaskStartToCloseTimeout = defaultTaskStartToCloseTimeout; return this; } // Check to see if DefaultTaskStartToCloseTimeout property is set internal bool IsSetDefaultTaskStartToCloseTimeout() { return this.defaultTaskStartToCloseTimeout != null; } /// <summary> /// If set, specifies the default maximum duration for executions of this workflow type. You can override this default when starting an /// execution through the <a>StartWorkflowExecution</a> Action or <c>StartChildWorkflowExecution</c> <a>Decision</a>. The duration is specified /// in seconds. The valid values are integers greater than or equal to 0. Unlike some of the other timeout parameters in Amazon SWF, you cannot /// specify a value of "NONE" for <c>defaultExecutionStartToCloseTimeout</c>; there is a one-year max limit on the time that a workflow /// execution can run. Exceeding this limit will always cause the workflow execution to time out. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string DefaultExecutionStartToCloseTimeout { get { return this.defaultExecutionStartToCloseTimeout; } set { this.defaultExecutionStartToCloseTimeout = value; } } /// <summary> /// Sets the DefaultExecutionStartToCloseTimeout property /// </summary> /// <param name="defaultExecutionStartToCloseTimeout">The value to set for the DefaultExecutionStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDefaultExecutionStartToCloseTimeout(string defaultExecutionStartToCloseTimeout) { this.defaultExecutionStartToCloseTimeout = defaultExecutionStartToCloseTimeout; return this; } // Check to see if DefaultExecutionStartToCloseTimeout property is set internal bool IsSetDefaultExecutionStartToCloseTimeout() { return this.defaultExecutionStartToCloseTimeout != null; } /// <summary> /// If set, specifies the default task list to use for scheduling decision tasks for executions of this workflow type. This default is used only /// if a task list is not provided when starting the execution through the <a>StartWorkflowExecution</a> Action or /// <c>StartChildWorkflowExecution</c> <a>Decision</a>. /// /// </summary> public TaskList DefaultTaskList { get { return this.defaultTaskList; } set { this.defaultTaskList = value; } } /// <summary> /// Sets the DefaultTaskList property /// </summary> /// <param name="defaultTaskList">The value to set for the DefaultTaskList property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDefaultTaskList(TaskList defaultTaskList) { this.defaultTaskList = defaultTaskList; return this; } // Check to see if DefaultTaskList property is set internal bool IsSetDefaultTaskList() { return this.defaultTaskList != null; } /// <summary> /// If set, specifies the default policy to use for the child workflow executions when a workflow execution of this type is terminated, by /// calling the <a>TerminateWorkflowExecution</a> action explicitly or due to an expired timeout. This default can be overridden when starting a /// workflow execution using the <a>StartWorkflowExecution</a> action or the <c>StartChildWorkflowExecution</c> <a>Decision</a>. The supported /// child policies are: <ul> <li><b>TERMINATE:</b> the child executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b> a request to cancel /// will be attempted for each child execution by recording a <c>WorkflowExecutionCancelRequested</c> event in its history. It is up to the /// decider to take appropriate actions when it receives an execution history with this event. </li> <li><b>ABANDON:</b> no action will be /// taken. The child executions will continue to run.</li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TERMINATE, REQUEST_CANCEL, ABANDON</description> /// </item> /// </list> /// </para> /// </summary> public string DefaultChildPolicy { get { return this.defaultChildPolicy; } set { this.defaultChildPolicy = value; } } /// <summary> /// Sets the DefaultChildPolicy property /// </summary> /// <param name="defaultChildPolicy">The value to set for the DefaultChildPolicy property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RegisterWorkflowTypeRequest WithDefaultChildPolicy(string defaultChildPolicy) { this.defaultChildPolicy = defaultChildPolicy; return this; } // Check to see if DefaultChildPolicy property is set internal bool IsSetDefaultChildPolicy() { return this.defaultChildPolicy != null; } } }
//------------------------------------------------------------------------------- // <copyright file="AbortingMessageHandlingIntegration.cs" company="Multimedia Solutions AG"> // Copyright (c) MMS AG 2011-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using NUnit.Framework; using ServiceBus.Pipeline; using ServiceBus.Testing; [TestFixture] public class AbortingMessageHandlingIntegration { private const string SenderEndpointName = "Sender"; private const string ReceiverEndpointName = "Receiver"; private Context context; private HandlerRegistrySimulator registry; private MessageUnit sender; private MessageUnit receiver; [SetUp] public void SetUp() { this.context = new Context(); this.registry = new HandlerRegistrySimulator(this.context); this.sender = new MessageUnit(new EndpointConfiguration().Endpoint(SenderEndpointName).Concurrency(1)) .Use(MessagingFactory.Create()) .Use(new AlwaysRouteToDestination(Queue.Create(ReceiverEndpointName))) .Use(this.registry); this.receiver = new MessageUnit(new EndpointConfiguration().Endpoint(ReceiverEndpointName).Concurrency(1)) .Use(MessagingFactory.Create()) .Use(this.registry); this.SetUpNecessaryInfrastructure(); this.sender.StartAsync().Wait(); this.receiver.StartAsync().Wait(); } [TearDown] public void TearDown() { this.sender.StopAsync().Wait(); this.receiver.StopAsync().Wait(); } [Test] public async Task WhenPipelineAbortedAsync_ShouldNotContinueToSyncHandler() { await this.sender.Send(new Message { AbortAsync = true, AbortSync = false, Bar = 42 }); await this.context.Wait(asyncHandlerCalls: 1, handlerCalls: 0, lastHandlerCalls: 0); this.context.AsyncHandlerCalls.Should().BeInvokedOnce(); this.context.HandlerCalls.Should().NotBeInvoked(); this.context.LastHandlerCalls.Should().NotBeInvoked(); } [Test] public async Task WhenPipelineAbortedSync_ShouldNotContinueToLastHandler() { await this.sender.Send(new Message { AbortAsync = false, AbortSync = true, Bar = 42 }); await this.context.Wait(asyncHandlerCalls: 1, handlerCalls: 1, lastHandlerCalls: 0); this.context.AsyncHandlerCalls.Should().BeInvokedOnce(); this.context.HandlerCalls.Should().BeInvokedOnce(); this.context.LastHandlerCalls.Should().NotBeInvoked(); } [Test] public async Task WhenPipelineNotAborted_ShouldExecuteAllHandler() { await this.sender.Send(new Message { AbortAsync = false, AbortSync = false, Bar = 42 }); await this.context.Wait(asyncHandlerCalls: 1, handlerCalls: 1, lastHandlerCalls: 1); this.context.AsyncHandlerCalls.Should().BeInvokedOnce(); this.context.HandlerCalls.Should().BeInvokedOnce(); this.context.LastHandlerCalls.Should().BeInvokedOnce(); } private void SetUpNecessaryInfrastructure() { var manager = NamespaceManager.Create(); if (manager.QueueExists(SenderEndpointName)) { manager.DeleteQueue(SenderEndpointName); } manager.CreateQueue(SenderEndpointName); if (manager.QueueExists(ReceiverEndpointName)) { manager.DeleteQueue(ReceiverEndpointName); } manager.CreateQueue(ReceiverEndpointName); } public class HandlerRegistrySimulator : HandlerRegistry { private readonly Context context; public HandlerRegistrySimulator(Context context) { this.context = context; } public override IReadOnlyCollection<object> GetHandlers(Type messageType) { if (messageType == typeof(Message)) { return this.ConsumeWith( new AsyncMessageHandler(this.context), new MessageHandler(this.context).AsAsync(), new LastHandler(this.context)); } return this.ConsumeAll(); } } public class AsyncMessageHandler : IHandleMessageAsync<Message> { private readonly Context context; public AsyncMessageHandler(Context context) { this.context = context; } public Task Handle(Message message, IBusForHandler bus) { this.context.AsyncHandlerCalled(); if (message.AbortAsync) { bus.DoNotContinueDispatchingCurrentMessageToHandlers(); } return Task.FromResult(0); } } public class MessageHandler : IHandleMessage<Message> { private readonly Context context; public MessageHandler(Context context) { this.context = context; } public void Handle(Message message, IBusForHandler bus) { this.context.HandlerCalled(); if (message.AbortSync) { bus.DoNotContinueDispatchingCurrentMessageToHandlers(); } } } public class LastHandler : IHandleMessageAsync<Message> { private readonly Context context; public LastHandler(Context context) { this.context = context; } public Task Handle(Message message, IBusForHandler bus) { this.context.LastHandlerCalled(); return Task.FromResult(0); } } public class Message { public bool AbortAsync { get; set; } public bool AbortSync { get; set; } public int Bar { get; set; } } public class Context { private long asyncHandlerCalled; private long handlerCalled; private long lastHandlerCalled; public int AsyncHandlerCalls { get { return (int)Interlocked.Read(ref this.asyncHandlerCalled); } } public int HandlerCalls { get { return (int)Interlocked.Read(ref this.handlerCalled); } } public int LastHandlerCalls { get { return (int)Interlocked.Read(ref this.lastHandlerCalled); } } public void AsyncHandlerCalled() { Interlocked.Increment(ref this.asyncHandlerCalled); } public void HandlerCalled() { Interlocked.Increment(ref this.handlerCalled); } public void LastHandlerCalled() { Interlocked.Increment(ref this.lastHandlerCalled); } public Task Wait(int asyncHandlerCalls, int handlerCalls, int lastHandlerCalls) { var task1 = Task.Run(() => SpinWait.SpinUntil(() => this.AsyncHandlerCalls >= asyncHandlerCalls && this.HandlerCalls >= handlerCalls && this.LastHandlerCalls >= lastHandlerCalls)); var task2 = Task.Delay(TimeSpan.FromSeconds(30)); return Task.WhenAny(task1, task2); } } } }
using System; using System.IO; using Axiom.Core; using Axiom.MathLib; using System.Runtime.InteropServices; namespace Axiom.Graphics { /// <summary> /// This class is intended to allow a clean stream interface for writing to hardware buffers. /// An instance of this would be returned by one of the HardwareBuffer.Lock methods, which would /// allow easily and safely writing to a hardware buffer without having to use unsafe code. /// </summary> public class BufferStream { #region Fields /// <summary> /// Current position (as a byte offset) into the stream. /// </summary> protected long position; /// <summary> /// Pointer to the raw data we will be writing to. /// </summary> protected IntPtr data; /// <summary> /// Reference to the hardware buffer who owns this stream. /// </summary> protected HardwareBuffer owner; /// <summary> /// Temp array. /// </summary> protected ValueType[] tmp = new ValueType[1]; #endregion Fields #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="owner">Reference to the hardware buffer who owns this stream.</param> /// <param name="data">Pointer to the raw data we will be writing to.</param> internal BufferStream(HardwareBuffer owner, IntPtr data) { this.data = data; this.owner = owner; } #endregion Constructor #region Methods /// <summary> /// Length (in bytes) of this stream. /// </summary> public long Length { get { return owner.Size; } } /// <summary> /// Current position of the stream. /// </summary> public long Position { get { return position; } set { if(value > this.Length) { throw new ArgumentException("Position of the buffer may not exceed the length."); } position = value; } } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public int Read(byte[] buffer, int offset, int count) { // TODO: Add BufferStream.Read implementation return 0; } public void Write(Vector3 vec, int offset) { tmp[0] = vec; Write(tmp, offset); } public void Write(Vector4 vec, int offset) { tmp[0] = vec; Write(tmp, offset); } public void Write(float val, int offset) { tmp[0] = val; Write(tmp, offset); } public void Write(short val, int offset) { tmp[0] = val; Write(tmp, offset); } public void Write(byte val, int offset) { tmp[0] = val; Write(tmp, offset); } public void Write(System.Array val) { Write(val, 0); } public void Write(System.Array val, int offset) { int count = Marshal.SizeOf(val.GetType().GetElementType()) * val.Length; Write(val, offset, count); } /// <summary> /// /// </summary> /// <param name="val"></param> /// <param name="offset"></param> /// <param name="count"></param> public void Write(System.Array val, int offset, int count) { // can't write to unlocked buffers if (!owner.IsLocked) { throw new AxiomException("Cannot write to a buffer stream when the buffer is not locked."); } long newOffset = position + offset; // ensure we won't go past the end of the stream if (newOffset + count > this.Length) { throw new AxiomException("Unable to write data past the end of a BufferStream"); } // pin the array so we can get a pointer to it GCHandle handle = GCHandle.Alloc(val, GCHandleType.Pinned); unsafe { // get byte pointers for the source and target byte* b = (byte*)handle.AddrOfPinnedObject().ToPointer(); byte* dataPtr = (byte*)data.ToPointer(); // copy the data from the source to the target for (int i = 0; i < count; i++) { dataPtr[i + newOffset] = b[i]; } } handle.Free(); } /// <summary> /// Moves the "cursor" position within the buffer. /// </summary> /// <param name="offset">Offset (in bytes) to move from the current position.</param> /// <returns></returns> public long Seek(long offset) { return Seek(offset, SeekOrigin.Current); } /// <summary> /// Moves the "cursor" position within the buffer. /// </summary> /// <param name="offset">Number of bytes to move.</param> /// <param name="origin">How to treat the offset amount.</param> /// <returns></returns> public long Seek(long offset, SeekOrigin origin) { switch(origin) { // seeks from the beginning of the stream case SeekOrigin.Begin: position = offset; break; // offset is from the current stream position case SeekOrigin.Current: if(position + offset > this.Length) { throw new ArgumentException("Cannot seek past the end of the stream."); } position = position + offset; break; // seeks backwards from the end of the stream case SeekOrigin.End: if(this.Length - offset < 0) { throw new ArgumentException("Cannot seek past the beginning of the stream."); } position = this.Length - offset; break; } return position; } #endregion Methods } }
using ClosedXML.Excel; using NUnit.Framework; using System; using System.Globalization; using System.Threading; namespace ClosedXML_Tests.Excel.CalcEngine { [TestFixture] public class InformationTests { [OneTimeSetUp] public void SetCultureInfo() { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); } #region IsBlank Tests [Test] public void IsBlank_MultipleAllEmpty_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(true, actual); } } [Test] public void IsBlank_MultipleAllFill_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "1"; ws.Cell("A2").Value = "1"; ws.Cell("A3").Value = "1"; var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_MultipleMixedFill_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "1"; ws.Cell("A3").Value = "1"; var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_Single_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = " "; var actual = ws.Evaluate("=IsBlank(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_Single_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var actual = ws.Evaluate("=IsBlank(A1)"); Assert.AreEqual(true, actual); } } #endregion IsBlank Tests #region IsEven Tests [Test] public void IsEven_Single_False() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 1; ws.Cell("A2").Value = 1.2; ws.Cell("A3").Value = 3; var actual = ws.Evaluate("=IsEven(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsEven(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsEven(A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsEven_Single_True() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 4; ws.Cell("A2").Value = 0.2; ws.Cell("A3").Value = 12.2; var actual = ws.Evaluate("=IsEven(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsEven(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsEven(A3)"); Assert.AreEqual(true, actual); } } #endregion IsEven Tests #region IsLogical Tests [Test] public void IsLogical_Simpe_False() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 123; var actual = ws.Evaluate("=IsLogical(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsLogical_Simple_True() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = true; var actual = ws.Evaluate("=IsLogical(A1)"); Assert.AreEqual(true, actual); } } #endregion IsLogical Tests [Test] public void IsNA() { object actual; actual = XLWorkbook.EvaluateExpr("ISNA(#N/A)"); Assert.AreEqual(true, actual); actual = XLWorkbook.EvaluateExpr("ISNA(#REF!)"); Assert.AreEqual(false, actual); } #region IsNotText Tests [Test] public void IsNotText_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=IsNonText(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsNotText_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Comma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = true; //Bool Value ws.Cell("A6").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsNonText(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A3)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A4)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A5)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A6)"); Assert.AreEqual(true, actual); } } #endregion IsNotText Tests #region IsNumber Tests [Test] public void IsNumber_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; //String Value ws.Cell("A2").Value = true; //Bool Value var actual = ws.Evaluate("=IsNumber(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsNumber(A2)"); Assert.AreEqual(false, actual); } } [Test] public void IsNumber_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Coma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsNumber(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A3)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A4)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A5)"); Assert.AreEqual(true, actual); } } #endregion IsNumber Tests #region IsOdd Test [Test] public void IsOdd_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 4; ws.Cell("A2").Value = 0.2; ws.Cell("A3").Value = 12.2; var actual = ws.Evaluate("=IsOdd(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsOdd(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsOdd(A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsOdd_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 1; ws.Cell("A2").Value = 1.2; ws.Cell("A3").Value = 3; var actual = ws.Evaluate("=IsOdd(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsOdd(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsOdd(A3)"); Assert.AreEqual(true, actual); } } #endregion IsOdd Test [Test] public void IsRef() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; ws.Cell("B1").FormulaA1 = "ISREF(A1)"; ws.Cell("B2").FormulaA1 = "ISREF(5)"; ws.Cell("B3").FormulaA1 = "ISREF(YEAR(TODAY()))"; bool actual; actual = ws.Cell("B1").GetValue<bool>(); Assert.AreEqual(true, actual); actual = ws.Cell("B2").GetValue<bool>(); Assert.AreEqual(false, actual); actual = ws.Cell("B3").GetValue<bool>(); Assert.AreEqual(false, actual); } } #region IsText Tests [Test] public void IsText_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Comma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = true; //Bool Value ws.Cell("A6").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsText(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A3)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A4)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A5)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A6)"); Assert.AreEqual(false, actual); } } [Test] public void IsText_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=IsText(A1)"); Assert.AreEqual(true, actual); } } #endregion IsText Tests #region N Tests [Test] public void N_Date_SerialNumber() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var testedDate = DateTime.Now; ws.Cell("A1").Value = testedDate; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(testedDate.ToOADate(), actual); } } [Test] public void N_False_Zero() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = false; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(0, actual); } } [Test] public void N_Number_Number() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var testedValue = 123; ws.Cell("A1").Value = testedValue; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(testedValue, actual); } } [Test] public void N_String_Zero() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(0, actual); } } [Test] public void N_True_One() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = true; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(1, actual); } } #endregion N Tests } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Transactions { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Transactions; /// <summary> /// Grid cache transaction implementation. /// </summary> internal sealed class TransactionImpl : IDisposable { /** Metadatas. */ private object[] _metas; /** Unique transaction ID.*/ private readonly long _id; /** Transactions facade. */ private readonly TransactionsImpl _txs; /** TX concurrency. */ private readonly TransactionConcurrency _concurrency; /** TX isolation. */ private readonly TransactionIsolation _isolation; /** Timeout. */ private readonly TimeSpan _timeout; /** TX label. */ private readonly string _label; /** Start time. */ private readonly DateTime _startTime; /** Owning thread ID. */ private readonly int _threadId; /** Originating node ID. */ private readonly Guid _nodeId; /** State holder. */ private StateHolder _state; // ReSharper disable once InconsistentNaming /** Transaction for this thread. */ [ThreadStatic] private static TransactionImpl THREAD_TX; /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> /// <param name="txs">Transactions.</param> /// <param name="concurrency">TX concurrency.</param> /// <param name="isolation">TX isolation.</param> /// <param name="timeout">Timeout.</param> /// <param name="label">TX label.</param> /// <param name="nodeId">The originating node identifier.</param> /// <param name="bindToThread">Bind transaction to current thread or not.</param> public TransactionImpl(long id, TransactionsImpl txs, TransactionConcurrency concurrency, TransactionIsolation isolation, TimeSpan timeout, string label, Guid nodeId, bool bindToThread = true) { _id = id; _txs = txs; _concurrency = concurrency; _isolation = isolation; _timeout = timeout; _label = label; _nodeId = nodeId; _startTime = DateTime.Now; _threadId = Thread.CurrentThread.ManagedThreadId; if (bindToThread) THREAD_TX = this; } /// <summary> /// Transaction assigned to this thread. /// </summary> public static Transaction Current { get { var tx = THREAD_TX; if (tx == null) return null; if (tx.IsClosed) { THREAD_TX = null; return null; } return new Transaction(tx); } } /// <summary> /// Executes prepare step of the two phase commit. /// </summary> public void Prepare() { lock (this) { ThrowIfClosed(); _txs.TxPrepare(this); } } /// <summary> /// Commits this tx and closes it. /// </summary> public void Commit() { lock (this) { ThrowIfClosed(); _state = new StateHolder(_txs.TxCommit(this)); } } /// <summary> /// Rolls this tx back and closes it. /// </summary> public void Rollback() { lock (this) { ThrowIfClosed(); _state = new StateHolder(_txs.TxRollback(this)); } } /// <summary> /// Sets the rollback only flag. /// </summary> public bool SetRollbackOnly() { lock (this) { ThrowIfClosed(); return _txs.TxSetRollbackOnly(this); } } /// <summary> /// Gets a value indicating whether this instance is rollback only. /// </summary> public bool IsRollbackOnly { get { lock (this) { var state0 = _state == null ? State : _state.State; return state0 == TransactionState.MarkedRollback || state0 == TransactionState.RollingBack || state0 == TransactionState.RolledBack; } } } /// <summary> /// Gets the state. /// </summary> public TransactionState State { get { lock (this) { return _state != null ? _state.State : _txs.TxState(this); } } } /// <summary> /// Gets the isolation. /// </summary> public TransactionIsolation Isolation { get { return _isolation; } } /// <summary> /// Gets the concurrency. /// </summary> public TransactionConcurrency Concurrency { get { return _concurrency; } } /// <summary> /// Gets the timeout. /// </summary> public TimeSpan Timeout { get { return _timeout; } } /// <summary> /// Label of current transaction. /// </summary> public string Label { get { return _label; } } /// <summary> /// Gets the start time. /// </summary> public DateTime StartTime { get { return _startTime; } } /// <summary> /// Gets the node identifier. /// </summary> public Guid NodeId { get { return _nodeId; } } /// <summary> /// Gets the thread identifier. /// </summary> public long ThreadId { get { return _threadId; } } /// <summary> /// Adds a new metadata. /// </summary> public void AddMeta<TV>(string name, TV val) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { int putIdx = -1; for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) { _metas[i + 1] = val; return; } if (_metas[i] == null && putIdx == -1) // Preserve empty space index. putIdx = i; } // No meta with the given name found. if (putIdx == -1) { // Extend array. putIdx = _metas.Length; object[] metas0 = new object[putIdx + 2]; Array.Copy(_metas, metas0, putIdx); _metas = metas0; } _metas[putIdx] = name; _metas[putIdx + 1] = val; } else _metas = new object[] { name, val }; } } /// <summary> /// Gets metadata by name. /// </summary> public TV Meta<TV>(string name) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) return (TV)_metas[i + 1]; } } return default(TV); } } /// <summary> /// Removes metadata by name. /// </summary> public TV RemoveMeta<TV>(string name) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) { TV val = (TV)_metas[i + 1]; _metas[i] = null; _metas[i + 1] = null; return val; } } } return default(TV); } } /// <summary> /// Commits tx in async mode. /// </summary> internal Task CommitAsync() { lock (this) { ThrowIfClosed(); return CloseWhenComplete(_txs.CommitAsync(this)); } } /// <summary> /// Rolls tx back in async mode. /// </summary> internal Task RollbackAsync() { lock (this) { ThrowIfClosed(); return CloseWhenComplete(_txs.RollbackAsync(this)); } } /// <summary> /// Transaction ID. /// </summary> internal long Id { get { return _id; } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Dispose should not throw.")] public void Dispose() { try { Close(); } catch(IgniteIllegalStateException) { _state = new StateHolder(TransactionState.Unknown); } finally { GC.SuppressFinalize(this); } } /// <summary> /// Gets a value indicating whether this transaction is closed. /// </summary> private bool IsClosed { get { return _state != null; } } /// <summary> /// Gets the closed exception. /// </summary> private InvalidOperationException GetClosedException() { return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Transaction {0} is closed, state is {1}", Id, State)); } /// <summary> /// Creates a task via provided factory if IsClosed is false; otherwise, return a task with an error. /// </summary> internal Task GetTask(Func<Task> operationFactory) { lock (this) { return IsClosed ? GetExceptionTask() : operationFactory(); } } /// <summary> /// Gets the task that throws an exception. /// </summary> private Task GetExceptionTask() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(GetClosedException()); return tcs.Task; } /// <summary> /// Closes the transaction and releases unmanaged resources. /// </summary> private void Close() { lock (this) { _state = _state ?? new StateHolder((TransactionState) _txs.TxClose(this)); } } /// <summary> /// Throws and exception if transaction is closed. /// </summary> private void ThrowIfClosed() { if (IsClosed) throw GetClosedException(); } /// <summary> /// Closes this transaction upon task completion. /// </summary> private Task CloseWhenComplete(Task task) { return task.ContWith(x => Close()); } /** <inheritdoc /> */ ~TransactionImpl() { Dispose(); } /// <summary> /// State holder. /// </summary> private class StateHolder { /** Current state. */ private readonly TransactionState _state; /// <summary> /// Constructor. /// </summary> /// <param name="state">State.</param> public StateHolder(TransactionState state) { _state = state; } /// <summary> /// Current state. /// </summary> public TransactionState State { get { return _state; } } } } }
namespace java.util.zip { [global::MonoJavaBridge.JavaClass()] public partial class Deflater : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Deflater(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override void finalize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "finalize", "()V", ref global::java.util.zip.Deflater._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void reset() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "reset", "()V", ref global::java.util.zip.Deflater._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual bool finished() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.zip.Deflater.staticClass, "finished", "()Z", ref global::java.util.zip.Deflater._m2); } private static global::MonoJavaBridge.MethodId _m3; public virtual void end() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "end", "()V", ref global::java.util.zip.Deflater._m3); } public new byte[] Input { set { setInput(value); } } private static global::MonoJavaBridge.MethodId _m4; public virtual void setInput(byte[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setInput", "([B)V", ref global::java.util.zip.Deflater._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void setInput(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setInput", "([BII)V", ref global::java.util.zip.Deflater._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public new long BytesWritten { get { return getBytesWritten(); } } private static global::MonoJavaBridge.MethodId _m6; public virtual long getBytesWritten() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.zip.Deflater.staticClass, "getBytesWritten", "()J", ref global::java.util.zip.Deflater._m6); } private static global::MonoJavaBridge.MethodId _m7; public virtual bool needsInput() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.zip.Deflater.staticClass, "needsInput", "()Z", ref global::java.util.zip.Deflater._m7); } public new byte[] Dictionary { set { setDictionary(value); } } private static global::MonoJavaBridge.MethodId _m8; public virtual void setDictionary(byte[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setDictionary", "([B)V", ref global::java.util.zip.Deflater._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public virtual void setDictionary(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setDictionary", "([BII)V", ref global::java.util.zip.Deflater._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public new int Adler { get { return getAdler(); } } private static global::MonoJavaBridge.MethodId _m10; public virtual int getAdler() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.zip.Deflater.staticClass, "getAdler", "()I", ref global::java.util.zip.Deflater._m10); } public new int TotalIn { get { return getTotalIn(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual int getTotalIn() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.zip.Deflater.staticClass, "getTotalIn", "()I", ref global::java.util.zip.Deflater._m11); } public new long BytesRead { get { return getBytesRead(); } } private static global::MonoJavaBridge.MethodId _m12; public virtual long getBytesRead() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.zip.Deflater.staticClass, "getBytesRead", "()J", ref global::java.util.zip.Deflater._m12); } public new int TotalOut { get { return getTotalOut(); } } private static global::MonoJavaBridge.MethodId _m13; public virtual int getTotalOut() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.zip.Deflater.staticClass, "getTotalOut", "()I", ref global::java.util.zip.Deflater._m13); } public new int Level { set { setLevel(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual void setLevel(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setLevel", "(I)V", ref global::java.util.zip.Deflater._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public virtual void finish() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "finish", "()V", ref global::java.util.zip.Deflater._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual int deflate(byte[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.zip.Deflater.staticClass, "deflate", "([BII)I", ref global::java.util.zip.Deflater._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m17; public virtual int deflate(byte[] arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.zip.Deflater.staticClass, "deflate", "([B)I", ref global::java.util.zip.Deflater._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Strategy { set { setStrategy(value); } } private static global::MonoJavaBridge.MethodId _m18; public virtual void setStrategy(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.zip.Deflater.staticClass, "setStrategy", "(I)V", ref global::java.util.zip.Deflater._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; public Deflater(int arg0, bool arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.zip.Deflater._m19.native == global::System.IntPtr.Zero) global::java.util.zip.Deflater._m19 = @__env.GetMethodIDNoThrow(global::java.util.zip.Deflater.staticClass, "<init>", "(IZ)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.zip.Deflater.staticClass, global::java.util.zip.Deflater._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m20; public Deflater(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.zip.Deflater._m20.native == global::System.IntPtr.Zero) global::java.util.zip.Deflater._m20 = @__env.GetMethodIDNoThrow(global::java.util.zip.Deflater.staticClass, "<init>", "(I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.zip.Deflater.staticClass, global::java.util.zip.Deflater._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m21; public Deflater() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.zip.Deflater._m21.native == global::System.IntPtr.Zero) global::java.util.zip.Deflater._m21 = @__env.GetMethodIDNoThrow(global::java.util.zip.Deflater.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.zip.Deflater.staticClass, global::java.util.zip.Deflater._m21); Init(@__env, handle); } public static int DEFLATED { get { return 8; } } public static int NO_COMPRESSION { get { return 0; } } public static int BEST_SPEED { get { return 1; } } public static int BEST_COMPRESSION { get { return 9; } } public static int DEFAULT_COMPRESSION { get { return -1; } } public static int FILTERED { get { return 1; } } public static int HUFFMAN_ONLY { get { return 2; } } public static int DEFAULT_STRATEGY { get { return 0; } } static Deflater() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.zip.Deflater.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/zip/Deflater")); } } }
/* * 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 NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using RAMDirectory = Lucene.Net.Store.RAMDirectory; namespace Lucene.Net.Search { /// <summary> A basic 'positive' Unit test class for the FieldCacheRangeFilter class. /// /// <p/> /// NOTE: at the moment, this class only tests for 'positive' results, /// it does not verify the results to ensure there are no 'false positives', /// nor does it adequately test 'negative' results. It also does not test /// that garbage in results in an Exception. /// </summary> [TestFixture] public class TestFieldCacheRangeFilter:BaseTestRangeFilter { public TestFieldCacheRangeFilter(System.String name):base(name) { } public TestFieldCacheRangeFilter():base() { } [Test] public virtual void TestRangeFilterId() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int medId = ((maxId - minId) / 2); System.String minIP = Pad(minId); System.String maxIP = Pad(maxId); System.String medIP = Pad(medId); int numDocs = reader.NumDocs(); Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + maxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, medIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - minId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, maxIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, maxIP, T, F), numDocs).ScoreDocs; Assert.AreEqual(maxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, medIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - minId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, minIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, medIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, minIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, minIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, medIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); } [Test] public virtual void TestFieldCacheRangeFilterRand() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); System.String minRP = Pad(signedIndex.minR); System.String maxRP = Pad(signedIndex.maxR); int numDocs = reader.NumDocs(); Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test extremes, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but biggest"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but smallest"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but extremes"); // unbounded result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "smallest and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, maxRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "biggest and down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not smallest, but up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not biggest, but down"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, minRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, minRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, minRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, maxRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); } // byte-ranges cannot be tested, because all ranges are too big for bytes, need an extra range for that [Test] public virtual void TestFieldCacheRangeFilterShorts() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int numDocs = reader.NumDocs(); int medId = ((maxId - minId) / 2); System.Int16 minIdO = (short) minId; System.Int16 maxIdO = (short) maxId; System.Int16 medIdO = (short) medId; Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + maxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - minId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(maxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - minId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases System.Int16 tempAux = (short) System.Int16.MaxValue; result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", tempAux, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); System.Int16 tempAux2 = (short) System.Int16.MinValue; result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, tempAux2, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } [Test] public virtual void TestFieldCacheRangeFilterInts() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int numDocs = reader.NumDocs(); int medId = ((maxId - minId) / 2); System.Int32 minIdO = (System.Int32) minId; System.Int32 maxIdO = (System.Int32) maxId; System.Int32 medIdO = (System.Int32) medId; Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + maxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - minId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(maxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - minId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases System.Int32 tempAux = (System.Int32) System.Int32.MaxValue; result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", tempAux, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); System.Int32 tempAux2 = (System.Int32) System.Int32.MinValue; result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, tempAux2, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } [Test] public virtual void TestFieldCacheRangeFilterLongs() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int numDocs = reader.NumDocs(); int medId = ((maxId - minId) / 2); System.Int64 minIdO = (long) minId; System.Int64 maxIdO = (long) maxId; System.Int64 medIdO = (long) medId; Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + maxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - minId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(maxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - minId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases System.Int64 tempAux = (long) System.Int64.MaxValue; result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", tempAux, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); System.Int64 tempAux2 = (long) System.Int64.MinValue; result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, tempAux2, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } // float and double tests are a bit minimalistic, but its complicated, because missing precision [Test] public virtual void TestFieldCacheRangeFilterFloats() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int numDocs = reader.NumDocs(); System.Single minIdO = (float) (minId + .5f); System.Single medIdO = (float) ((float) minIdO + ((float) (maxId - minId)) / 2.0f); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs / 2, result.Length, "find all"); int count = 0; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, medIdO, F, T), numDocs).ScoreDocs; count += result.Length; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", medIdO, null, F, F), numDocs).ScoreDocs; count += result.Length; Assert.AreEqual(numDocs, count, "sum of two concenatted ranges"); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); System.Single tempAux = (float) System.Single.PositiveInfinity; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", tempAux, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); System.Single tempAux2 = (float) System.Single.NegativeInfinity; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, tempAux2, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); } [Test] public virtual void TestFieldCacheRangeFilterDoubles() { IndexReader reader = IndexReader.Open(signedIndex.index); IndexSearcher search = new IndexSearcher(reader); int numDocs = reader.NumDocs(); System.Double minIdO = (double) (minId + .5); System.Double medIdO = (double) ((float) minIdO + ((double) (maxId - minId)) / 2.0); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs / 2, result.Length, "find all"); int count = 0; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, medIdO, F, T), numDocs).ScoreDocs; count += result.Length; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", medIdO, null, F, F), numDocs).ScoreDocs; count += result.Length; Assert.AreEqual(numDocs, count, "sum of two concenatted ranges"); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); System.Double tempAux = (double) System.Double.PositiveInfinity; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", tempAux, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); System.Double tempAux2 = (double) System.Double.NegativeInfinity; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, tempAux2, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); } } }
// 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 Microsoft.Tools.ServiceModel.SvcUtil { using System; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.CodeDom.Compiler; using System.ServiceModel; using System.Runtime.Serialization; using System.Text; using System.Reflection; using System.Globalization; internal static class ToolConsole { #if DEBUG private static bool s_debug = false; #endif #if DEBUG internal static void SetOptions(bool debug) { ToolConsole.s_debug = debug; } #endif internal static void WriteLine(string str, int indent) { ToolStringBuilder toolStringBuilder = new ToolStringBuilder(indent); toolStringBuilder.WriteParagraph(str); } internal static void WriteLine(string str) { Console.WriteLine(str); } internal static void WriteLine() { Console.WriteLine(); } internal static void WriteError(string errMsg) { WriteError(errMsg, SR.Format(SR.Error)); } private static void WriteError(Exception e) { WriteError(e, SR.Format(SR.Error)); } internal static void WriteUnexpectedError(Exception e) { WriteError(SR.Format(SR.ErrUnexpectedError)); WriteError(e); } internal static void WriteInvalidDataContractError(InvalidDataContractException e) { WriteError(e); ToolConsole.WriteLine(); ToolConsole.WriteLine(SR.Format(SR.HintConsiderUseXmlSerializer, Options.Cmd.DataContractOnly, Options.Cmd.ImportXmlTypes)); } internal static void WriteUnexpectedError(string errMsg) { WriteError(SR.Format(SR.ErrUnexpectedError)); if (!string.IsNullOrEmpty(errMsg)) WriteError(errMsg); } internal static void WriteToolError(ToolArgumentException ae) { WriteError(ae); ToolMexException me = ae as ToolMexException; if (me != null) { string serviceUri = me.ServiceUri.AbsoluteUri; ToolConsole.WriteLine(); ToolConsole.WriteError(SR.Format(SR.WrnWSMExFailed, serviceUri), string.Empty); ToolConsole.WriteError(me.WSMexException, " "); if (me.HttpGetException != null) { ToolConsole.WriteLine(); ToolConsole.WriteError(SR.Format(SR.WrnHttpGetFailed, serviceUri), string.Empty); ToolConsole.WriteError(me.HttpGetException, " "); } } ToolConsole.WriteLine(SR.Format(SR.MoreHelp, Options.Abbr.Help)); } internal static void WriteToolError(ToolRuntimeException re) { WriteError(re); } internal static void WriteWarning(string message) { Console.Error.Write(SR.Format(SR.Warning)); Console.Error.WriteLine(message); Console.Error.WriteLine(); } private static void WriteError(string errMsg, string prefix) { Console.Error.Write(prefix); Console.Error.WriteLine(errMsg); Console.Error.WriteLine(); } internal static void WriteError(Exception e, string prefix) { #if DEBUG if (s_debug) { ToolConsole.WriteLine(); WriteError(e.ToString(), prefix); return; } #endif WriteError(e.Message, prefix); while (e.InnerException != null) { if (e.Message != e.InnerException.Message) { WriteError(e.InnerException.Message, " "); } e = e.InnerException; } } internal static void WriteHeader() { // Using CommonResStrings.WcfTrademarkForCmdLine for the trademark: the proper resource for command line tools. ToolConsole.WriteLine(SR.Format(SR.Logo, SR.WcfTrademarkForCmdLine, ThisAssembly.InformationalVersion, SR.CopyrightForCmdLine)); } internal static void WriteHelpText() { HelpGenerator.WriteUsage(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteCommonOptionsHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteXmlSerializerTypeGenerationHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteExamples(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); } private static class HelpGenerator { private static ToolStringBuilder s_exampleBuilder = new ToolStringBuilder(4); static HelpGenerator() { } // beforefeildInit internal static void WriteUsage() { ToolConsole.WriteLine(SR.Format(SR.HelpUsage1)); ToolConsole.WriteLine(); ToolConsole.WriteLine(SR.Format(SR.HelpUsage6)); } internal static void WriteXmlSerializerTypeGenerationHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpXmlSerializerTypeGenerationCategory)); helpCategory.Description = SR.Format(SR.HelpXmlSerializerTypeGenerationDescription, ThisAssembly.Title); helpCategory.Syntax = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntax, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.XmlSerializer, SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs = new ArgumentInfo[1]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput1); helpCategory.Options = new ArgumentInfo[3]; helpCategory.Options[0] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput2, Options.Abbr.Reference); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput3, Options.Cmd.DataContractOnly, Options.Abbr.ExcludeType); helpCategory.Options[2] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Out, SR.Format(SR.ParametersOut)); helpCategory.Options[2].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput4, Options.Abbr.Out); helpCategory.WriteHelp(); } internal static void WriteMetadataDownloadHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpMetadataDownloadCategory)); helpCategory.Description = SR.Format(SR.HelpMetadataDownloadDescription, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.Metadata, Options.Cmd.ToolConfig); helpCategory.Syntax = SR.Format(SR.HelpMetadataDownloadSyntax, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.Metadata, SR.Format(SR.HelpInputUrl), SR.Format(SR.HelpInputEpr)); helpCategory.Inputs = new ArgumentInfo[2]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputUrl)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpMetadataDownloadSyntaxInput1); helpCategory.Inputs[1] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputEpr)); helpCategory.Inputs[1].HelpText = SR.Format(SR.HelpMetadataDownloadSyntaxInput2); helpCategory.WriteHelp(); } internal static void WriteMetadataExportHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpMetadataExportCategory)); helpCategory.Description = SR.Format(SR.HelpMetadataExportDescription, ThisAssembly.Title, Options.Cmd.ServiceName, Options.Cmd.DataContractOnly); helpCategory.Syntax = SR.Format(SR.HelpMetadataExportSyntax, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.Metadata, Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName), Options.Cmd.DataContractOnly, SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs = new ArgumentInfo[1]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpMetadataExportSyntaxInput1); helpCategory.Options = new ArgumentInfo[4]; helpCategory.Options[0] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName)); helpCategory.Options[0].HelpText = SR.Format(SR.HelpServiceNameExport, Options.Abbr.Reference); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpReferenceOther, Options.Abbr.Reference); helpCategory.Options[2] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.DataContractOnly); helpCategory.Options[2].HelpText = SR.Format(SR.HelpDataContractOnly, Options.Abbr.DataContractOnly); helpCategory.Options[3] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[3].HelpText = SR.Format(SR.HelpExcludeTypeExport, Options.Abbr.ExcludeType, Options.Abbr.DataContractOnly); helpCategory.WriteHelp(); } internal static void WriteValidationHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpValidationCategory)); helpCategory.Description = SR.Format(SR.HelpValidationDescription, Options.Cmd.ServiceName); helpCategory.Syntax = SR.Format(SR.HelpValidationSyntax, ThisAssembly.Title, Options.Cmd.Validate, Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName), SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs = new ArgumentInfo[1]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpValidationSyntaxInput1); helpCategory.Options = new ArgumentInfo[5]; helpCategory.Options[0] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Validate); helpCategory.Options[0].HelpText = SR.Format(SR.HelpValidate, Options.Cmd.ServiceName, Options.Abbr.Validate); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpServiceNameValidate, Options.Abbr.Reference); helpCategory.Options[2] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[2].HelpText = SR.Format(SR.HelpReferenceOther, Options.Abbr.Reference); helpCategory.Options[3] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.DataContractOnly); helpCategory.Options[3].HelpText = SR.Format(SR.HelpDataContractOnly, Options.Abbr.DataContractOnly); helpCategory.Options[4] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[4].HelpText = SR.Format(SR.HelpValidationExcludeTypeExport, Options.Abbr.ExcludeType, Options.Abbr.DataContractOnly); helpCategory.WriteHelp(); } internal static void WriteCommonOptionsHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpCommonOptionsCategory)); var options = new List<ArgumentInfo>(); ArgumentInfo option; option = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Target, SR.Format(SR.ParametersOutputType)); option.HelpText = SR.Format(SR.HelpTargetOutputType, Options.Targets.Code, Options.Targets.Metadata, Options.Targets.XmlSerializer); options.Add(option); option = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Directory, SR.Format(SR.ParametersDirectory)); option.HelpText = SR.Format(SR.HelpDirectory, Options.Abbr.Directory); options.Add(option); option = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.NoLogo); option.HelpText = SR.Format(SR.HelpNologo); options.Add(option); option = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Help); option.HelpText = SR.Format(SR.HelpHelp, Options.Abbr.Help); options.Add(option); helpCategory.Options = options.ToArray(); helpCategory.WriteHelp(); } internal static void WriteCodeGenerationHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpCodeGenerationCategory)); helpCategory.Description = SR.Format(SR.HelpCodeGenerationDescription, ThisAssembly.Title); helpCategory.Syntax = SR.Format(SR.HelpCodeGenerationSyntax, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.Code, SR.Format(SR.HelpInputMetadataDocumentPath), SR.Format(SR.HelpInputUrl), SR.Format(SR.HelpInputEpr)); helpCategory.Inputs = new ArgumentInfo[3]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputMetadataDocumentPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput1); helpCategory.Inputs[1] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputUrl)); helpCategory.Inputs[1].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput2); helpCategory.Inputs[2] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputEpr)); helpCategory.Inputs[2].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput3); helpCategory.Options = new ArgumentInfo[26]; helpCategory.Options[0] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Out, SR.Format(SR.ParametersOut)); helpCategory.Options[0].HelpText = SR.Format(SR.HelpOut, Options.Abbr.Out); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Config, SR.Format(SR.ParametersConfig)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpConfig); helpCategory.Options[2] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.MergeConfig); helpCategory.Options[2].HelpText = SR.Format(SR.HelpMergeConfig); helpCategory.Options[3] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.NoConfig); helpCategory.Options[3].HelpText = SR.Format(SR.HelpNoconfig); helpCategory.Options[4] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.DataContractOnly); helpCategory.Options[4].HelpText = SR.Format(SR.HelpCodeGenerationDataContractOnly, Options.Abbr.DataContractOnly); helpCategory.Options[5] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Language, SR.Format(SR.ParametersLanguage)); helpCategory.Options[5].BeginGroup = true; helpCategory.Options[5].HelpText = SR.Format(SR.HelpLanguage, Options.Abbr.Language); helpCategory.Options[6] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Namespace, SR.Format(SR.ParametersNamespace)); helpCategory.Options[6].HelpText = SR.Format(SR.HelpNamespace, Options.Abbr.Namespace); helpCategory.Options[7] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.MessageContract); helpCategory.Options[7].BeginGroup = true; helpCategory.Options[7].HelpText = SR.Format(SR.HelpMessageContract, Options.Abbr.MessageContract); helpCategory.Options[8] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.EnableDataBinding); helpCategory.Options[8].HelpText = SR.Format(SR.HelpEnableDataBinding, Options.Abbr.EnableDataBinding); helpCategory.Options[9] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Serializable); helpCategory.Options[9].HelpText = SR.Format(SR.HelpSerializable, Options.Abbr.Serializable); helpCategory.Options[10] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Async); helpCategory.Options[10].HelpText = SR.Format(SR.HelpAsync, Options.Abbr.Async); helpCategory.Options[11] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Internal); helpCategory.Options[11].HelpText = SR.Format(SR.HelpInternal, Options.Abbr.Internal); helpCategory.Options[12] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[12].BeginGroup = true; helpCategory.Options[12].HelpText = SR.Format(SR.HelpReferenceCodeGeneration, Options.Abbr.Reference); helpCategory.Options[13] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.CollectionType, SR.Format(SR.ParametersCollectionType)); helpCategory.Options[13].HelpText = SR.Format(SR.HelpCollectionType, Options.Abbr.CollectionType); helpCategory.Options[14] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[14].HelpText = SR.Format(SR.HelpExcludeTypeCodeGeneration, Options.Abbr.ExcludeType); helpCategory.Options[15] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Nostdlib); helpCategory.Options[15].HelpText = SR.Format(SR.HelpNostdlib); helpCategory.Options[16] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Serializer, SerializerMode.Auto.ToString()); helpCategory.Options[16].BeginGroup = true; helpCategory.Options[16].HelpText = SR.Format(SR.HelpAutoSerializer, Options.Abbr.Serializer); helpCategory.Options[17] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Serializer, SerializerMode.DataContractSerializer.ToString()); helpCategory.Options[17].HelpText = SR.Format(SR.HelpDataContractSerializer); helpCategory.Options[18] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Serializer, SerializerMode.XmlSerializer.ToString()); helpCategory.Options[18].HelpText = SR.Format(SR.HelpXmlSerializer); helpCategory.Options[19] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.ImportXmlTypes); helpCategory.Options[19].HelpText = SR.Format(SR.HelpImportXmlType, Options.Abbr.ImportXmlTypes); helpCategory.Options[20] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.UseSerializerForFaults); helpCategory.Options[20].HelpText = SR.Format(SR.HelpUseSerializerForFaults, Options.Abbr.UseSerializerForFaults); helpCategory.Options[21] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.TargetClientVersion, TargetClientVersionMode.Version30.ToString()); helpCategory.Options[21].BeginGroup = true; helpCategory.Options[21].HelpText = SR.Format(SR.HelpVersion30TargetClientVersion, Options.Abbr.TargetClientVersion); helpCategory.Options[22] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.TargetClientVersion, TargetClientVersionMode.Version35.ToString()); helpCategory.Options[22].HelpText = SR.Format(SR.HelpVersion35TargetClientVersion, Options.Abbr.TargetClientVersion); helpCategory.Options[23] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Wrapped); helpCategory.Options[23].HelpText = SR.Format(SR.HelpWrapped); helpCategory.Options[24] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.ServiceContract); helpCategory.Options[24].HelpText = SR.Format(SR.HelpCodeGenerationServiceContract, Options.Abbr.ServiceContract); helpCategory.Options[25] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.SyncOnly); helpCategory.Options[25].HelpText = SR.Format(SR.HelpSyncOnly); helpCategory.WriteHelp(); } internal static void WriteExamples() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpExamples)); helpCategory.WriteHelp(); WriteExample(SR.Format(SR.HelpExamples18), SR.Format(SR.HelpExamples19)); } private static void WriteExample(string syntax, string explanation) { ToolConsole.WriteLine(string.Format(CultureInfo.InvariantCulture, " {0}", syntax)); s_exampleBuilder.WriteParagraph(string.Format(CultureInfo.InvariantCulture, " {0}", explanation)); ToolConsole.WriteLine(); } private class ArgumentInfo { private const string argHelpPrefix = " "; private const string argHelpSeperator = " - "; internal static ArgumentInfo CreateInputHelpInfo(string input) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = input; return argInfo; } internal static ArgumentInfo CreateFlagHelpInfo(string option) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = String.Format(CultureInfo.InvariantCulture, "/{0}", option); return argInfo; } internal static ArgumentInfo CreateParameterHelpInfo(string option, string optionUse) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = String.Format(CultureInfo.InvariantCulture, "/{0}:{1}", option, optionUse); return argInfo; } private bool _beginGroup; private string _name; private string _helpText; public bool BeginGroup { get { return _beginGroup; } set { _beginGroup = value; } } public string Name { get { return _name; } } public string HelpText { set { _helpText = value; } } private string GenerateHelp(string pattern) { return string.Format(CultureInfo.InvariantCulture, pattern, _name, _helpText); } private static int CalculateMaxNameLength(ArgumentInfo[] arguments) { int maxNameLength = 0; foreach (ArgumentInfo argument in arguments) { if (argument.Name.Length > maxNameLength) { maxNameLength = argument.Name.Length; } } return maxNameLength; } public static void WriteArguments(ArgumentInfo[] arguments) { int maxArgumentnLength = CalculateMaxNameLength(arguments); int helpTextIndent = argHelpPrefix.Length + maxArgumentnLength + argHelpSeperator.Length; string helpPattern = argHelpPrefix + "{0, -" + maxArgumentnLength + "}" + argHelpSeperator + "{1}"; ToolStringBuilder builder = new ToolStringBuilder(helpTextIndent); foreach (ArgumentInfo argument in arguments) { if (argument.BeginGroup) ToolConsole.WriteLine(); string optionHelp = argument.GenerateHelp(helpPattern); builder.WriteParagraph(optionHelp); } } } private class HelpCategory { static HelpCategory() { try { bool junk = Console.CursorVisible; if (Console.WindowWidth > 75) s_nameMidpoint = Console.WindowWidth / 3; else s_nameMidpoint = 25; } catch { s_nameMidpoint = 25; } } private static ToolStringBuilder s_categoryBuilder = new ToolStringBuilder(4); private static int s_nameMidpoint; private int _nameStart; private string _name; private string _description = null; private string _syntax = null; private ArgumentInfo[] _options; private ArgumentInfo[] _inputs; public HelpCategory(string name) { Tool.Assert(name != null, "Name should never be null"); _name = name; _nameStart = s_nameMidpoint - (name.Length / 2); } public string Description { set { _description = value; } } public string Syntax { set { _syntax = value; } } public ArgumentInfo[] Options { get { return _options; } set { _options = value; } } public ArgumentInfo[] Inputs { get { return _inputs; } set { _inputs = value; } } public void WriteHelp() { int start = s_nameMidpoint; ToolConsole.WriteLine(new string(' ', _nameStart) + _name); ToolConsole.WriteLine(); if (_description != null) { s_categoryBuilder.WriteParagraph(_description); ToolConsole.WriteLine(); } if (_syntax != null) { s_categoryBuilder.WriteParagraph(_syntax); ToolConsole.WriteLine(); } if (_inputs != null) { ArgumentInfo.WriteArguments(_inputs); ToolConsole.WriteLine(); } if (_options != null) { ToolConsole.WriteLine(SR.Format(SR.HelpOptions)); ToolConsole.WriteLine(); ArgumentInfo.WriteArguments(_options); ToolConsole.WriteLine(); } } } } private class ToolStringBuilder { private int _indentLength; private int _cursorLeft; private int _lineWidth; private StringBuilder _stringBuilder; public ToolStringBuilder(int indentLength) { _indentLength = indentLength; } private void Reset() { _stringBuilder = new StringBuilder(); _cursorLeft = GetConsoleCursorLeft(); _lineWidth = GetBufferWidth(); } public void WriteParagraph(string text) { this.Reset(); this.AppendParagraph(text); ToolConsole.WriteLine(_stringBuilder.ToString()); _stringBuilder = null; } private void AppendParagraph(string text) { Tool.Assert(_stringBuilder != null, "stringBuilder cannot be null"); int index = 0; while (index < text.Length) { this.AppendWord(text, ref index); this.AppendWhitespace(text, ref index); } } private void AppendWord(string text, ref int index) { // If we're at the beginning of a new line we should indent. if ((_cursorLeft == 0) && (index != 0)) AppendIndent(); int wordLength = FindWordLength(text, index); // Now that we know how long the string is we can: // 1. print it on the current line if we have enough space // 2. print it on the next line if we don't have space // on the current line and it will fit on the next line // 3. print whatever will fit on the current line // and overflow to the next line. if (wordLength < this.HangingLineWidth) { if (wordLength > this.BufferWidth) { this.AppendLineBreak(); this.AppendIndent(); } _stringBuilder.Append(text, index, wordLength); _cursorLeft += wordLength; } else { AppendWithOverflow(text, ref index, ref wordLength); } index += wordLength; } private void AppendWithOverflow(string test, ref int start, ref int wordLength) { do { _stringBuilder.Append(test, start, this.BufferWidth); start += this.BufferWidth; wordLength -= this.BufferWidth; this.AppendLineBreak(); if (wordLength > 0) this.AppendIndent(); } while (wordLength > this.BufferWidth); if (wordLength > 0) { _stringBuilder.Append(test, start, wordLength); _cursorLeft += wordLength; } } private void AppendWhitespace(string text, ref int index) { while ((index < text.Length) && char.IsWhiteSpace(text[index])) { if (BufferWidth == 0) { this.AppendLineBreak(); } // For each whitespace character: // 1. If we're at a newline character we insert // a new line and reset the cursor. // 2. If the whitespace character is at the beginning of a new // line, we insert an indent instead of the whitespace // 3. Insert the whitespace if (AtNewLine(text, index)) { this.AppendLineBreak(); index += Environment.NewLine.Length; } else if (_cursorLeft == 0 && index != 0) { AppendIndent(); index++; } else { _stringBuilder.Append(text[index]); index++; _cursorLeft++; } } } private void AppendIndent() { _stringBuilder.Append(' ', _indentLength); _cursorLeft += _indentLength; } private void AppendLineBreak() { if (BufferWidth != 0) _stringBuilder.AppendLine(); _cursorLeft = 0; } private int BufferWidth { get { return _lineWidth - _cursorLeft; } } private int HangingLineWidth { get { return _lineWidth - _indentLength; } } private static int FindWordLength(string text, int index) { for (int end = index; end < text.Length; end++) { if (char.IsWhiteSpace(text[end])) return end - index; } return text.Length - index; } private static bool AtNewLine(string text, int index) { if ((index + Environment.NewLine.Length) > text.Length) { return false; } for (int i = 0; i < Environment.NewLine.Length; i++) { if (Environment.NewLine[i] != text[index + i]) { return false; } } return true; } private static int GetConsoleCursorLeft() { try { return Console.CursorLeft; } catch { return 0; } } private static int GetBufferWidth() { try { bool junk = Console.CursorVisible; return Console.BufferWidth; } catch { return int.MaxValue; } } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.ComponentModel; using System.Xml.Serialization; using System.Collections.Generic; using System.Drawing.Design; using System.Linq; using Microsoft.MultiverseInterfaceStudio.FrameXml.Controls; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization { /// Generated from Ui.xsd into two pieces and merged here. /// Manually modified later - DO NOT REGENERATE /// <remarks/> [System.Xml.Serialization.XmlIncludeAttribute(typeof(FrameType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(TaxiRouteFrameType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(MinimapType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(CooldownType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(GameTooltipType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(WorldFrameType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(MovieFrameType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ScrollFrameType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ScrollingMessageFrameType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(MessageFrameType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(BrowserType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(ModelType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(PlayerModelType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(TabardModelType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(DressUpModelType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ColorSelectType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(EditBoxType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(SliderType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(StatusBarType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ButtonType))] //[System.Xml.Serialization.XmlIncludeAttribute(typeof(UnitButtonType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(CheckButtonType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(FontStringType))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(TextureType))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "3.5.20706.1")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.multiverse.net/ui")] [System.Xml.Serialization.XmlRootAttribute("LayoutFrame", Namespace = "http://www.multiverse.net/ui", IsNullable = false)] public partial class LayoutFrameType : SerializationObject { private string inheritsField; private bool virtualField; public LayoutFrameType() { this.virtualField = false; this.Properties = new PropertyBag(this); } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] [Browsable(false)] public string name { get; set; } /// <remarks/> [XmlAttribute] [TypeConverter(typeof(InheritsTypeConverter))] [Browsable(false)] public string inherits { get { return this.inheritsField; } set { this.inheritsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] [System.ComponentModel.DefaultValueAttribute(false)] [Category("Layout")] public bool @virtual { get { return this.virtualField; } set { this.virtualField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] [System.ComponentModel.DefaultValueAttribute(false)] [Category("Behavior")] public bool setAllPoints { get { return this.Properties.GetValue<bool>("setAllPoints"); } set { this.Properties["setAllPoints"] = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] [System.ComponentModel.DefaultValueAttribute(false)] [Category("Layout")] public bool hidden { get { return this.Properties.GetValue<bool>("hidden"); } set { this.Properties["hidden"] = value; } } private List<LayoutFrameTypeAnchors> anchors = new List<LayoutFrameTypeAnchors>(); [XmlIgnore] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Browsable(false)] public List<LayoutFrameTypeAnchors> AnchorsCollection { get { return anchors; } } protected override List<LayoutFrameTypeAnchors> GetAnchors() { return this.AnchorsCollection; } /// <summary> /// Gets or sets the parent. /// </summary> /// <value>The parent.</value> [Browsable(false)] [XmlIgnore] public LayoutFrameType Parent { get; set; } [Browsable(false)] [XmlIgnore] public IEnumerable<LayoutFrameType> Children { get { var result = new List<LayoutFrameType>(); foreach (var frames in this.Controls.OfType<FrameTypeFrames>()) { result.AddRange(frames.Controls.OfType<LayoutFrameType>()); } foreach (var layers in this.LayersList) { foreach (var layer in layers.Layer) { result.AddRange(layer.Layerables.OfType<LayoutFrameType>()); } } return result; } } /// <summary> /// Gets the expanded name of the object (placeholders are replaced) /// </summary> /// <value>The expanded name of the object.</value> [Browsable(false)] [XmlIgnore] public string ExpandedName { get { string parentName = this.Parent != null ? this.Parent.ExpandedName : null; return GetExpandedName(name, parentName); } } public static string GetExpandedName(string name, string parentName) { if (name == null) return null; if (parentName == null) return name; return name.Replace("$parent", parentName); } } }
using System; using System.Collections.Generic; #if !NOT_UNITY3D using JetBrains.Annotations; #endif namespace Zenject { // Zero parameters public class PlaceholderFactory<TValue> : PlaceholderFactoryBase<TValue>, IFactory<TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create() { return CreateInternal(new List<TypeValuePair>()); } protected sealed override IEnumerable<Type> ParamTypes { get { yield break; } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TValue> : PlaceholderFactory<TValue> { } // One parameter public class PlaceholderFactory<TParam1, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TValue> : PlaceholderFactory<TParam1, TValue> { } // Two parameters public class PlaceholderFactory<TParam1, TParam2, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param1, TParam2 param2) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TValue> : PlaceholderFactory<TParam1, TParam2, TValue> { } // Three parameters public class PlaceholderFactory<TParam1, TParam2, TParam3, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TParam3, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param1, TParam2 param2, TParam3 param3) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2), InjectUtil.CreateTypePair(param3) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); yield return typeof(TParam3); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TParam3, TValue> : PlaceholderFactory<TParam1, TParam2, TParam3, TValue> { } // Four parameters public class PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2), InjectUtil.CreateTypePair(param3), InjectUtil.CreateTypePair(param4) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); yield return typeof(TParam3); yield return typeof(TParam4); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TParam3, TParam4, TValue> : PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TValue> { } // Five parameters public class PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2), InjectUtil.CreateTypePair(param3), InjectUtil.CreateTypePair(param4), InjectUtil.CreateTypePair(param5) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); yield return typeof(TParam3); yield return typeof(TParam4); yield return typeof(TParam5); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> { } // Six parameters public class PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> { // Note: Most of the time you should not override this method and should instead // use BindFactory<>.FromIFactory if you want to do some custom logic #if !NOT_UNITY3D [NotNull] #endif public virtual TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2), InjectUtil.CreateTypePair(param3), InjectUtil.CreateTypePair(param4), InjectUtil.CreateTypePair(param5), InjectUtil.CreateTypePair(param6) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); yield return typeof(TParam3); yield return typeof(TParam4); yield return typeof(TParam5); yield return typeof(TParam6); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> { } // Ten parameters public class PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> : PlaceholderFactoryBase<TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> { // If you were hoping to override this method, use BindFactory<>.ToFactory instead public virtual TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) { return CreateInternal( new List<TypeValuePair> { InjectUtil.CreateTypePair(param1), InjectUtil.CreateTypePair(param2), InjectUtil.CreateTypePair(param3), InjectUtil.CreateTypePair(param4), InjectUtil.CreateTypePair(param5), InjectUtil.CreateTypePair(param6), InjectUtil.CreateTypePair(param7), InjectUtil.CreateTypePair(param8), InjectUtil.CreateTypePair(param9), InjectUtil.CreateTypePair(param10) }); } protected sealed override IEnumerable<Type> ParamTypes { get { yield return typeof(TParam1); yield return typeof(TParam2); yield return typeof(TParam3); yield return typeof(TParam4); yield return typeof(TParam5); yield return typeof(TParam6); yield return typeof(TParam7); yield return typeof(TParam8); yield return typeof(TParam9); yield return typeof(TParam10); } } } [Obsolete("Zenject.Factory has been renamed to PlaceholderFactory. Zenject.Factory will be removed in future versions")] public class Factory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> : PlaceholderFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> { } }
// // System.Web.UI.WebControls.BaseDataList.cs // // Authors: // Gaurav Vaish (gvaish@iitk.ac.in) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // Sanjay Gupta (gsanjay@novell.com) // // (C) Gaurav Vaish (2001) // (C) 2003 Andreas Nahr // (C) 2004 Novell, Inc. (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Web; using System.Web.UI; using System.Web.Util; namespace System.Web.UI.WebControls { [DefaultEvent("SelectedIndexChanged")] [DefaultProperty("DataSource")] [Designer("System.Web.UI.Design.WebControls.BaseDataListDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))] public abstract class BaseDataList: WebControl { private static readonly object SelectedIndexChangedEvent = new object(); internal static string ItemCountViewStateKey = "_!ItemCount"; private DataKeyCollection dataKeys; private object dataSource; #if NET_2_0 bool inited; IDataSource currentSource; DataSourceSelectArguments selectArguments = null; bool requiresDataBinding; #endif public BaseDataList() : base() { } public static bool IsBindableType(Type type) { if(type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Decimal)) return true; return false; } public override ControlCollection Controls { get { EnsureChildControls(); return base.Controls; } } public override void DataBind() { #if NET_2_0 RequiresDataBinding = false; #endif OnDataBinding(EventArgs.Empty); } [WebCategory("Action")] [WebSysDescription("BaseDataList_OnSelectedIndexChanged")] public event EventHandler SelectedIndexChanged { add { Events.AddHandler(SelectedIndexChangedEvent, value); } remove { Events.RemoveHandler(SelectedIndexChangedEvent, value); } } #if !NET_2_0 [Bindable(true)] #endif [DefaultValue(-1)] [WebCategory("Layout")] [WebSysDescription("BaseDataList_CellPadding")] public virtual int CellPadding { get { if(!ControlStyleCreated) return -1; return ((TableStyle)ControlStyle).CellPadding; } set { ((TableStyle)ControlStyle).CellPadding = value; } } #if !NET_2_0 [Bindable(true)] #endif [DefaultValue(-1)] [WebCategory("Layout")] [WebSysDescription("BaseDataList_CellSpacing")] public virtual int CellSpacing { get { if(!ControlStyleCreated) return -1; return ((TableStyle)ControlStyle).CellSpacing; } set { ((TableStyle)ControlStyle).CellSpacing = value; } } [DefaultValue ("")] [WebCategory ("Accessibility")] [WebSysDescription ("Caption")] public virtual string Caption { get { object o = ViewState ["Caption"]; return (o != null) ? (string) o : ""; } set { ViewState ["Caption"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #endif [DefaultValue("")] [WebCategory("Data")] [WebSysDescription("BaseDataList_DataKeyField")] public virtual string DataKeyField { get { object o = ViewState["DataKeyField"]; if(o!=null) return (string)o; return String.Empty; } set { ViewState["DataKeyField"] = value; } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [WebSysDescription("BaseDataList_DataKeys")] public DataKeyCollection DataKeys { get { if( dataKeys==null ) dataKeys = new DataKeyCollection(DataKeysArray); return dataKeys; } } #if NET_2_0 [ThemeableAttribute (false)] #endif [DefaultValue("")] [WebCategory("Data")] [WebSysDescription("BaseDataList_DataMember")] public string DataMember { get { object o = ViewState["DataMember"]; if(o!=null) return (string)o; return String.Empty; } set { ViewState["DataMember"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #endif [Bindable(true)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [WebCategory("Data")] [WebSysDescription("BaseDataList_DataSource")] public virtual object DataSource { get { return dataSource; } set { if (value == null || value is IListSource || value is IEnumerable) { dataSource = value; #if NET_2_0 if (inited) OnDataPropertyChanged (); #endif } else { throw new ArgumentException (HttpRuntime.FormatResourceString ( "Invalid_DataSource_Type", ID)); } } } #if !NET_2_0 [Bindable(true)] #endif [DefaultValue(GridLines.Both)] [WebCategory("Appearance")] [WebSysDescription("BaseDataList_GridLines")] public virtual GridLines GridLines { get { if(ControlStyleCreated) return ((TableStyle)ControlStyle).GridLines; return GridLines.Both; } set { ((TableStyle)ControlStyle).GridLines = value; } } // LAMESPEC HorizontalAlign has a Category attribute, this should obviously be a WebCategory attribute // but is defined incorrectly in the MS framework #if !NET_2_0 [Bindable(true)] #endif [DefaultValue(HorizontalAlign.NotSet)] [Category("Layout")] [WebSysDescription("BaseDataList_HorizontalAlign")] public virtual HorizontalAlign HorizontalAlign { get { if(ControlStyleCreated) return ((TableStyle)ControlStyle).HorizontalAlign; return HorizontalAlign.NotSet; } set { ((TableStyle)ControlStyle).HorizontalAlign = value; } } protected ArrayList DataKeysArray { get { object o = ViewState["DataKeys"]; if(o == null) { o = new ArrayList(); ViewState["DataKeys"] = o; } return (ArrayList)o; } } protected override void AddParsedSubObject(object o) { // Preventing literal controls from being added as children. } protected override void CreateChildControls() { Controls.Clear(); if(ViewState[ItemCountViewStateKey]!=null) { CreateControlHierarchy(false); ClearChildViewState(); } } protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); Controls.Clear(); ClearChildViewState(); CreateControlHierarchy(true); ChildControlsCreated = true; TrackViewState(); } protected virtual void OnSelectedIndexChanged(EventArgs e) { if(Events != null) { EventHandler eh = (EventHandler)(Events[SelectedIndexChangedEvent]); if(eh!=null) eh(this, e); } } protected override void Render(HtmlTextWriter writer) { PrepareControlHierarchy(); RenderContents(writer); } protected abstract void PrepareControlHierarchy(); protected abstract void CreateControlHierarchy(bool useDataSource); #if NET_2_0 protected override void OnInit (EventArgs e) { base.OnInit(e); Page.PreLoad += new EventHandler (OnPagePreLoad); } void OnPagePreLoad (object sender, EventArgs e) { SubscribeSourceChangeEvent (); inited = true; } void SubscribeSourceChangeEvent () { IDataSource ds = GetDataSource (); if (currentSource != ds && currentSource != null) { currentSource.DataSourceChanged -= new EventHandler (OnDataSourceViewChanged); currentSource = ds; } if (ds != null) ds.DataSourceChanged += new EventHandler (OnDataSourceViewChanged); } protected override void OnLoad (EventArgs e) { if (IsBoundUsingDataSourceID && (!Page.IsPostBack || !EnableViewState)) RequiresDataBinding = true; base.OnLoad(e); } protected override void OnPreRender (EventArgs e) { EnsureDataBound (); base.OnPreRender (e); } protected bool IsBoundUsingDataSourceID { get { return DataSourceID.Length > 0; } } protected void EnsureDataBound () { if (RequiresDataBinding && IsBoundUsingDataSourceID) DataBind (); } IDataSource GetDataSource () { if (IsBoundUsingDataSourceID) { Control ctrl = NamingContainer.FindControl (DataSourceID); if (ctrl == null) throw new HttpException (string.Format ("A control with ID '{0}' could not be found.", DataSourceID)); if (!(ctrl is IDataSource)) throw new HttpException (string.Format ("The control with ID '{0}' is not a control of type IDataSource.", DataSourceID)); return (IDataSource) ctrl; } return DataSource as IDataSource; } protected IEnumerable GetData () { if (DataSource != null && IsBoundUsingDataSourceID) throw new HttpException ("Control bound using both DataSourceID and DataSource properties."); IDataSource ds = GetDataSource (); if (ds != null) return ds.GetView (DataMember).ExecuteSelect (SelectArguments); IEnumerable ie = DataSourceHelper.GetResolvedDataSource (DataSource, DataMember); if (ie != null) return ie; throw new HttpException (string.Format ("Unexpected data source type: {0}", DataSource.GetType())); } protected virtual void OnDataSourceViewChanged (object sender, EventArgs e) { RequiresDataBinding = true; } protected virtual void OnDataPropertyChanged () { RequiresDataBinding = true; SubscribeSourceChangeEvent (); } [DefaultValueAttribute ("")] [IDReferencePropertyAttribute (typeof(System.Web.UI.DataSourceControl))] [ThemeableAttribute (false)] public virtual string DataSourceID { get { object o = ViewState ["DataSourceID"]; if (o != null) return (string)o; return String.Empty; } set { ViewState ["DataSourceID"] = value; if (inited) OnDataPropertyChanged (); } } protected bool Initialized { get { return inited; } } protected bool RequiresDataBinding { get { return requiresDataBinding; } set { requiresDataBinding = value; } } protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments () { return DataSourceSelectArguments.Empty; } protected DataSourceSelectArguments SelectArguments { get { if (selectArguments == null) selectArguments = CreateDataSourceSelectArguments (); return selectArguments; } } internal IEnumerable GetResolvedDataSource () { return GetData (); } #else internal IEnumerable GetResolvedDataSource () { if (DataSource != null) return DataSourceHelper.GetResolvedDataSource (DataSource, DataMember); else return null; } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Orleans.LogConsistency; using System.Diagnostics; using Microsoft.Extensions.Logging; using Orleans.Serialization; using Orleans.MultiCluster; using Orleans.Runtime; using Orleans.GrainDirectory; namespace Orleans.EventSourcing.Common { /// <summary> /// A general template for constructing log view adaptors that are based on /// a sequentially read and written primary. We use this to construct /// a variety of different log-consistency providers, all following the same basic pattern /// (read and write latest view from/to primary, and send notifications after writing). ///<para> /// Note that the log itself is transient, i.e. not actually saved to storage - only the latest view and some /// metadata (the log position, and write flags) is stored in the primary. /// It is safe to interleave calls to this adaptor (using grain scheduler only, of course). /// </para> ///<para> /// Subclasses override ReadAsync and WriteAsync to read from / write to primary. /// Calls to the primary are serialized, i.e. never interleave. /// </para> /// </summary> /// <typeparam name="TLogView">The user-defined view of the log</typeparam> /// <typeparam name="TLogEntry">The type of the log entries</typeparam> /// <typeparam name="TSubmissionEntry">The type of submission entries stored in pending queue</typeparam> public abstract class PrimaryBasedLogViewAdaptor<TLogView, TLogEntry, TSubmissionEntry> : ILogViewAdaptor<TLogView, TLogEntry> where TLogView : class, new() where TLogEntry : class where TSubmissionEntry : SubmissionEntry<TLogEntry> { /// <summary> /// Set confirmed view the initial value (a view of the empty log) /// </summary> protected abstract void InitializeConfirmedView(TLogView initialstate); /// <summary> /// Read cached global state. /// </summary> protected abstract TLogView LastConfirmedView(); /// <summary> /// Read version of cached global state. /// </summary> protected abstract int GetConfirmedVersion(); /// <summary> /// Read the latest primary state. Must block/retry until successful. /// Should not throw exceptions, but record them in <see cref="LastPrimaryIssue"/> /// </summary> /// <returns></returns> protected abstract Task ReadAsync(); /// <summary> /// Apply pending entries to the primary. Must block/retry until successful. /// Should not throw exceptions, but record them in <see cref="LastPrimaryIssue"/> /// </summary> protected abstract Task<int> WriteAsync(); /// <summary> /// Create a submission entry for the submitted log entry. /// Using a type parameter so we can add protocol-specific info to this class. /// </summary> /// <returns></returns> protected abstract TSubmissionEntry MakeSubmissionEntry(TLogEntry entry); /// <summary> /// Whether this cluster supports submitting updates /// </summary> protected virtual bool SupportSubmissions { get { return true; } } /// <summary> /// Handle protocol messages. /// </summary> protected virtual Task<ILogConsistencyProtocolMessage> OnMessageReceived(ILogConsistencyProtocolMessage payload) { // subclasses that define custom protocol messages must override this throw new NotImplementedException(); } public virtual Task<IReadOnlyList<TLogEntry>> RetrieveLogSegment(int fromVersion, int length) { throw new NotSupportedException(); } /// <summary> /// Handle notification messages. Override this to handle notification subtypes. /// </summary> protected virtual void OnNotificationReceived(INotificationMessage payload) { var msg = payload as VersionNotificationMessage; if (msg != null) { if (msg.Version > lastVersionNotified) lastVersionNotified = msg.Version; return; } var batchmsg = payload as BatchedNotificationMessage; if (batchmsg != null) { foreach (var bm in batchmsg.Notifications) OnNotificationReceived(bm); return; } // subclass should have handled this in override throw new ProtocolTransportException(string.Format("message type {0} not handled by OnNotificationReceived", payload.GetType().FullName)); } /// <summary> /// The last version we have been notified of /// </summary> private int lastVersionNotified; /// <summary> /// Process stored notifications during worker cycle. Override to handle notification subtypes. /// </summary> protected virtual void ProcessNotifications() { if (lastVersionNotified > this.GetConfirmedVersion()) { Services.Log(LogLevel.Debug, "force refresh because of version notification v{0}", lastVersionNotified); needRefresh = true; } } /// <summary> /// Merge two notification messages, for batching. Override to handle notification subtypes. /// </summary> protected virtual INotificationMessage Merge(INotificationMessage earliermessage, INotificationMessage latermessage) { return new VersionNotificationMessage() { Version = latermessage.Version }; } /// <summary> /// The grain that is using this adaptor. /// </summary> protected ILogViewAdaptorHost<TLogView, TLogEntry> Host { get; private set; } /// <summary> /// The runtime services required for implementing notifications between grain instances in different cluster. /// </summary> protected ILogConsistencyProtocolServices Services { get; private set; } private const int max_notification_batch_size = 10000; /// <summary> /// Construct an instance, for the given parameters. /// </summary> protected PrimaryBasedLogViewAdaptor(ILogViewAdaptorHost<TLogView, TLogEntry> host, TLogView initialstate, ILogConsistencyProtocolServices services) { Debug.Assert(host != null && services != null && initialstate != null); this.Host = host; this.Services = services; InitializeConfirmedView(initialstate); worker = new BatchWorkerFromDelegate(Work); } /// <inheritdoc/> public virtual Task PreOnActivate() { Services.Log(LogLevel.Trace, "PreActivation Started"); // this flag indicates we have not done an initial load from storage yet // we do not act on this yet, but wait until after user OnActivate has run. needInitialRead = true; Services.Log(LogLevel.Trace, "PreActivation Complete"); return Task.CompletedTask; } public virtual Task PostOnActivate() { Services.Log(LogLevel.Trace, "PostActivation Started"); // start worker, if it has not already happened if (needInitialRead) worker.Notify(); Services.Log(LogLevel.Trace, "PostActivation Complete"); return Task.CompletedTask; } /// <inheritdoc/> public virtual async Task PostOnDeactivate() { Services.Log(LogLevel.Trace, "Deactivation Started"); while (!worker.IsIdle()) { await worker.WaitForCurrentWorkToBeServiced(); } Services.Log(LogLevel.Trace, "Deactivation Complete"); } // the currently submitted, unconfirmed entries. private readonly List<TSubmissionEntry> pending = new List<TSubmissionEntry>(); /// called at beginning of WriteAsync to the current tentative state protected TLogView CopyTentativeState() { var state = TentativeView; tentativeStateInternal = null; // to avoid aliasing return state; } /// called at beginning of WriteAsync to the current batch of updates protected TSubmissionEntry[] GetCurrentBatchOfUpdates() { return pending.ToArray(); // must use a copy } /// called at beginning of WriteAsync to get current number of pending updates protected int GetNumberPendingUpdates() { return pending.Count; } /// <summary> /// Tentative State. Represents Stable State + effects of pending updates. /// Computed lazily (null if not in use) /// </summary> private TLogView tentativeStateInternal; /// <summary> /// A flag that indicates to the worker that the client wants to refresh the state /// </summary> private bool needRefresh; /// <summary> /// A flag that indicates that we have not read global state at all yet, and should do so /// </summary> private bool needInitialRead; /// <summary> /// Background worker which asynchronously sends operations to the leader /// </summary> private BatchWorker worker; /// statistics gathering. Is null unless stats collection is turned on. protected LogConsistencyStatistics stats = null; /// For use by protocols. Determines if this cluster is part of the configured multicluster. protected bool IsMyClusterJoined() { return true; } /// <summary> /// Block until this cluster is joined to the multicluster. /// </summary> protected async Task EnsureClusterJoinedAsync() { while (!IsMyClusterJoined()) { Services.Log(LogLevel.Debug, "Waiting for join"); await Task.Delay(5000); } } /// <inheritdoc /> public void Submit(TLogEntry logEntry) { if (!SupportSubmissions) throw new InvalidOperationException("provider does not support submissions on cluster " + Services.MyClusterId); if (stats != null) stats.EventCounters["SubmitCalled"]++; Services.Log(LogLevel.Trace, "Submit"); SubmitInternal(DateTime.UtcNow, logEntry); worker.Notify(); } /// <inheritdoc /> public void SubmitRange(IEnumerable<TLogEntry> logEntries) { if (!SupportSubmissions) throw new InvalidOperationException("Provider does not support submissions on cluster " + Services.MyClusterId); if (stats != null) stats.EventCounters["SubmitRangeCalled"]++; Services.Log(LogLevel.Trace, "SubmitRange"); var time = DateTime.UtcNow; foreach (var e in logEntries) SubmitInternal(time, e); worker.Notify(); } /// <inheritdoc /> public Task<bool> TryAppend(TLogEntry logEntry) { if (!SupportSubmissions) throw new InvalidOperationException("Provider does not support submissions on cluster " + Services.MyClusterId); if (stats != null) stats.EventCounters["TryAppendCalled"]++; Services.Log(LogLevel.Trace, "TryAppend"); var promise = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); SubmitInternal(DateTime.UtcNow, logEntry, GetConfirmedVersion() + pending.Count, promise); worker.Notify(); return promise.Task; } /// <inheritdoc /> public Task<bool> TryAppendRange(IEnumerable<TLogEntry> logEntries) { if (!SupportSubmissions) throw new InvalidOperationException("Provider does not support submissions on cluster " + Services.MyClusterId); if (stats != null) stats.EventCounters["TryAppendRangeCalled"]++; Services.Log(LogLevel.Trace, "TryAppendRange"); var promise = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); var time = DateTime.UtcNow; var pos = GetConfirmedVersion() + pending.Count; bool first = true; foreach (var e in logEntries) { SubmitInternal(time, e, pos++, first ? promise : null); first = false; } worker.Notify(); return promise.Task; } private const int unconditional = -1; private void SubmitInternal(DateTime time, TLogEntry logentry, int conditionalPosition = unconditional, TaskCompletionSource<bool> resultPromise = null) { // create a submission entry var submissionentry = this.MakeSubmissionEntry(logentry); submissionentry.SubmissionTime = time; submissionentry.ResultPromise = resultPromise; submissionentry.ConditionalPosition = conditionalPosition; // add submission to queue pending.Add(submissionentry); // if we have a tentative state in use, update it if (this.tentativeStateInternal != null) { try { Host.UpdateView(this.tentativeStateInternal, logentry); } catch (Exception e) { Services.CaughtUserCodeException("UpdateView", nameof(SubmitInternal), e); } } try { Host.OnViewChanged(true, false); } catch (Exception e) { Services.CaughtUserCodeException("OnViewChanged", nameof(SubmitInternal), e); } } /// <inheritdoc /> public TLogView TentativeView { get { if (stats != null) stats.EventCounters["TentativeViewCalled"]++; if (tentativeStateInternal == null) CalculateTentativeState(); return tentativeStateInternal; } } /// <inheritdoc /> public TLogView ConfirmedView { get { if (stats != null) stats.EventCounters["ConfirmedViewCalled"]++; return LastConfirmedView(); } } /// <inheritdoc /> public int ConfirmedVersion { get { if (stats != null) stats.EventCounters["ConfirmedVersionCalled"]++; return GetConfirmedVersion(); } } /// <summary> /// Called from network /// </summary> /// <param name="payLoad"></param> /// <returns></returns> public async Task<ILogConsistencyProtocolMessage> OnProtocolMessageReceived(ILogConsistencyProtocolMessage payLoad) { var notificationMessage = payLoad as INotificationMessage; if (notificationMessage != null) { Services.Log(LogLevel.Debug, "NotificationReceived v{0}", notificationMessage.Version); OnNotificationReceived(notificationMessage); // poke worker so it will process the notifications worker.Notify(); return null; } else { //it's a protocol message return await OnMessageReceived(payLoad); } } /// <summary> /// method is virtual so subclasses can add their own events /// </summary> public virtual void EnableStatsCollection() { stats = new LogConsistencyStatistics() { EventCounters = new Dictionary<string, long>(), StabilizationLatenciesInMsecs = new List<int>() }; stats.EventCounters.Add("TentativeViewCalled", 0); stats.EventCounters.Add("ConfirmedViewCalled", 0); stats.EventCounters.Add("ConfirmedVersionCalled", 0); stats.EventCounters.Add("SubmitCalled", 0); stats.EventCounters.Add("SubmitRangeCalled", 0); stats.EventCounters.Add("TryAppendCalled", 0); stats.EventCounters.Add("TryAppendRangeCalled", 0); stats.EventCounters.Add("ConfirmSubmittedEntriesCalled", 0); stats.EventCounters.Add("SynchronizeNowCalled", 0); stats.EventCounters.Add("WritebackEvents", 0); stats.StabilizationLatenciesInMsecs = new List<int>(); } /// <summary> /// Disable stats collection /// </summary> public void DisableStatsCollection() { stats = null; } /// <summary> /// Get states /// </summary> /// <returns></returns> public LogConsistencyStatistics GetStats() { return stats; } private void CalculateTentativeState() { // copy the master this.tentativeStateInternal = (TLogView)Services.SerializationManager.DeepCopy(LastConfirmedView()); // Now apply all operations in pending foreach (var u in this.pending) try { Host.UpdateView(this.tentativeStateInternal, u.Entry); } catch (Exception e) { Services.CaughtUserCodeException("UpdateView", nameof(CalculateTentativeState), e); } } /// <summary> /// batch worker performs reads from and writes to global state. /// only one work cycle is active at any time. /// </summary> internal async Task Work() { Services.Log(LogLevel.Debug, "<1 ProcessNotifications"); var version = GetConfirmedVersion(); ProcessNotifications(); Services.Log(LogLevel.Debug, "<2 NotifyViewChanges"); NotifyViewChanges(ref version); bool haveToWrite = (pending.Count != 0); bool haveToRead = needInitialRead || (needRefresh && !haveToWrite); Services.Log(LogLevel.Debug, "<3 Storage htr={0} htw={1}", haveToRead, haveToWrite); try { if (haveToRead) { needRefresh = needInitialRead = false; // retrieving fresh version await ReadAsync(); NotifyViewChanges(ref version); } if (haveToWrite) { needRefresh = needInitialRead = false; // retrieving fresh version await UpdatePrimary(); if (stats != null) stats.EventCounters["WritebackEvents"]++; } } catch (Exception e) { // this should never happen - we are supposed to catch and store exceptions // in the correct place (LastPrimaryException or notification trackers) Services.ProtocolError($"Exception in Worker Cycle: {e}", true); } Services.Log(LogLevel.Debug, "<4 Done"); } /// <summary> /// This function stores the operations in the pending queue as a batch to the primary. /// Retries until some batch commits or there are no updates left. /// </summary> internal async Task UpdatePrimary() { int version = GetConfirmedVersion(); while (true) { try { // find stale conditional updates, remove them, and notify waiters RemoveStaleConditionalUpdates(); if (pending.Count == 0) return; // no updates to write. // try to write the updates as a batch var writeResult = await WriteAsync(); NotifyViewChanges(ref version, writeResult); // if the batch write failed due to conflicts, retry. if (writeResult == 0) continue; try { Host.OnViewChanged(false, true); } catch (Exception e) { Services.CaughtUserCodeException("OnViewChanged", nameof(UpdatePrimary), e); } // notify waiting promises of the success of conditional updates NotifyPromises(writeResult, true); // record stabilization time, for statistics if (stats != null) { var timeNow = DateTime.UtcNow; for (int i = 0; i < writeResult; i++) { var latency = timeNow - pending[i].SubmissionTime; stats.StabilizationLatenciesInMsecs.Add(latency.Milliseconds); } } // remove completed updates from queue pending.RemoveRange(0, writeResult); return; } catch (Exception e) { // this should never happen - we are supposed to catch and store exceptions // in the correct place (LastPrimaryException or notification trackers) Services.ProtocolError($"Exception in {nameof(UpdatePrimary)}: {e}", true); } } } private void NotifyViewChanges(ref int version, int numWritten = 0) { var v = GetConfirmedVersion(); bool tentativeChanged = (v != version + numWritten); bool confirmedChanged = (v != version); if (tentativeChanged || confirmedChanged) { tentativeStateInternal = null; // conservative. try { Host.OnViewChanged(tentativeChanged, confirmedChanged); } catch (Exception e) { Services.CaughtUserCodeException("OnViewChanged", nameof(NotifyViewChanges), e); } version = v; } } /// <summary> /// Store the last issue that occurred while reading or updating primary. /// Is null if successful. /// </summary> protected RecordedConnectionIssue LastPrimaryIssue; /// <inheritdoc /> public async Task Synchronize() { if (stats != null) stats.EventCounters["SynchronizeNowCalled"]++; Services.Log(LogLevel.Debug, "SynchronizeNowStart"); needRefresh = true; await worker.NotifyAndWaitForWorkToBeServiced(); Services.Log(LogLevel.Debug, "SynchronizeNowComplete"); } /// <inheritdoc/> public IEnumerable<TLogEntry> UnconfirmedSuffix { get { return pending.Select(te => te.Entry); } } /// <inheritdoc /> public async Task ConfirmSubmittedEntries() { if (stats != null) stats.EventCounters["ConfirmSubmittedEntriesCalled"]++; Services.Log(LogLevel.Debug, "ConfirmSubmittedEntriesStart"); if (pending.Count != 0) await worker.WaitForCurrentWorkToBeServiced(); Services.Log(LogLevel.Debug, "ConfirmSubmittedEntriesEnd"); } /// <summary> /// send failure notifications /// </summary> protected void NotifyPromises(int count, bool success) { for (int i = 0; i < count; i++) { var promise = pending[i].ResultPromise; if (promise != null) promise.SetResult(success); } } /// <summary> /// go through updates and remove all the conditional updates that have already failed /// </summary> protected void RemoveStaleConditionalUpdates() { int version = GetConfirmedVersion(); bool foundFailedConditionalUpdates = false; for (int pos = 0; pos < pending.Count; pos++) { var submissionEntry = pending[pos]; if (submissionEntry.ConditionalPosition != unconditional && (foundFailedConditionalUpdates || submissionEntry.ConditionalPosition != (version + pos))) { foundFailedConditionalUpdates = true; if (submissionEntry.ResultPromise != null) submissionEntry.ResultPromise.SetResult(false); } pos++; } if (foundFailedConditionalUpdates) { pending.RemoveAll(e => e.ConditionalPosition != unconditional); tentativeStateInternal = null; try { Host.OnViewChanged(true, false); } catch (Exception e) { Services.CaughtUserCodeException("OnViewChanged", nameof(RemoveStaleConditionalUpdates), e); } } } } /// <summary> /// Base class for submission entries stored in pending queue. /// </summary> /// <typeparam name="TLogEntry">The type of entry for this submission</typeparam> public class SubmissionEntry<TLogEntry> { /// <summary> The log entry that is submitted. </summary> public TLogEntry Entry; /// <summary> A timestamp for this submission. </summary> public DateTime SubmissionTime; /// <summary> For conditional updates, a promise that resolves once it is known whether the update was successful or not.</summary> public TaskCompletionSource<bool> ResultPromise; /// <summary> For conditional updates, the log position at which this update is supposed to be applied. </summary> public int ConditionalPosition; } }
namespace Microsoft.Protocols.TestSuites.MS_OXCRPC { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A base class contains common methods and fields used by test cases. /// </summary> [TestClass] [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Disable warning SA1401 because it should not be treated like a property.")] public class TestSuiteBase : TestClassBase { #region Variable /// <summary> /// Indicates the value is zero /// </summary> public const int ZERO = 0; /// <summary> /// Holds the value that represents the index of first object handle. /// </summary> protected const int FIRST = 0; /// <summary> /// Holds the value that represents no session context linking in ulIcxrLink. /// </summary> protected const uint UlIcxrLinkForNoSessionLink = 0xFFFFFFFF; /// <summary> /// Holds the value that represents a successful return value for operations /// </summary> protected const uint ResultSuccess = 0; /// <summary> /// Indicates value of OpenModeFlags, 2 means create. /// </summary> protected const uint OpenModeFlags = 2; /// <summary> /// The instance of the IMS_OXCRPCAdapter /// </summary> protected IMS_OXCRPCAdapter oxcrpcAdapter; /// <summary> /// The instance of the IMS_OXCRPCSUTControlAdapter /// </summary> protected IMS_OXCRPCSUTControlAdapter oxcrpcControlAdapter; /// <summary> /// User distinguished name (DN) /// </summary> protected string userDN; /// <summary> /// Uses this variable to hold the status code of InitializeRPC method /// </summary> protected bool returnStatus; /// <summary> /// Uses this variable to hold return value /// </summary> protected uint returnValue; /// <summary> /// Uses this variable to hold the return value when CXH is invalid /// </summary> protected uint returnValueForInvalidCXH; /// <summary> /// Contains the maximum length of the rgbAuxOut buffer. /// </summary> protected uint pcbAuxOut; /// <summary> /// On input, this parameter contains the maximum size of the rgbOut buffer. /// On output, this parameter contains the size of ROP response payload, /// including the size of the RPC_HEADER_EXT header in the rgbOut parameter. /// </summary> protected uint pcbOut; /// <summary> /// A Session Context Handle to be used with an AsyncEMSMDB interface. /// </summary> protected IntPtr pacxh; /// <summary> /// A Session Context Handle to be used with an EMSMDB interface. /// </summary> protected IntPtr pcxh; /// <summary> /// An invalid Session Context Handle to be used with an EMSMDB interface. /// </summary> protected IntPtr pcxhInvalid; /// <summary> /// A session index value that is associated with the CXH /// </summary> protected ushort picxr; /// <summary> /// Contains the time stamp in which the new Session Context was created. /// This parameter and ulIcxrLink are used for linking the Session Context created by EcDoConnectEx method with an existing Session Context. /// </summary> protected uint pulTimeStamp; /// <summary> /// A valid value for rgwClientVersion, 0x000c, 0x183e, 0x03e8 is specified in [MS-OXCRPC]. /// </summary> protected ushort[] rgwClientVersion = new ushort[3] { 0x000c, 0x183e, 0x03e8 }; /// <summary> /// The minimum client protocol version the server supports /// </summary> protected ushort[] rgwBestVersion = new ushort[3]; /// <summary> /// A table contains response handle of ROP commands /// </summary> protected List<List<uint>> responseSOHTable = new List<List<uint>>(); /// <summary> /// The response of the ROP commands /// </summary> protected IDeserializable response; /// <summary> /// A response handle of the ROP commands /// </summary> protected uint objHandle; /// <summary> /// Contains the ROP request payload /// </summary> protected byte[] rgbIn; /// <summary> /// Contains the ROP response payload /// </summary> protected byte[] rgbOut; /// <summary> /// Contains the auxiliary payload buffer /// </summary> protected byte[] rgbAuxOut; /// <summary> /// Holds the value represents USE_PER_MDB_REPLID_MAPPING flag that control the behavior of the RopLogon /// </summary> protected ulong userPrivilege; /// <summary> /// An unsigned integer represents value of no-used handle or auxInfo for specified RopCommands. /// </summary> protected uint unusedInfo = 0; /// <summary> /// An unsigned integer indicates the authentication level for creating RPC binding /// </summary> protected uint authenticationLevel; /// <summary> /// Define user name which can be used by client to access SUT. /// </summary> protected string userName; /// <summary> /// Define user password which can be used by client to access SUT. /// </summary> protected string password; /// <summary> /// An unsigned integer indicates specify authentication services by identifying the security package that provides the service /// </summary> protected uint authenticationService; /// <summary> /// A Boolean value indicates whether MAPI HTTP transport is set or not. /// </summary> protected bool transportIsMAPI; #endregion #region Test Case Initialization and Cleanup /// <summary> /// Initializes the test case before running it /// </summary> protected override void TestInitialize() { this.Site = TestClassBase.BaseTestSite; this.oxcrpcAdapter = this.Site.GetAdapter<IMS_OXCRPCAdapter>(); this.oxcrpcControlAdapter = this.Site.GetAdapter<IMS_OXCRPCSUTControlAdapter>(); this.transportIsMAPI = string.Compare(Common.GetConfigurationPropertyValue("TransportSeq", this.Site), "mapi_http", true, System.Globalization.CultureInfo.InvariantCulture) == 0; if (!this.transportIsMAPI) { this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.pcbOut = ConstValues.ValidpcbOut; this.rgbIn = new byte[0]; this.pcxh = IntPtr.Zero; this.pcxhInvalid = IntPtr.Zero; this.pacxh = IntPtr.Zero; this.pulTimeStamp = 0x00000000; this.responseSOHTable = new List<List<uint>>(); this.response = null; this.objHandle = 0; this.userDN = Common.GetConfigurationPropertyValue("AdminUserEssdn", this.Site); this.userName = Common.GetConfigurationPropertyValue("AdminUserName", this.Site); this.password = Common.GetConfigurationPropertyValue("AdminUserPassword", this.Site); // Holds the value represents USE_PER_MDB_REPLID_MAPPING flag that control the behavior of the RopLogon this.userPrivilege = 0x01000000; #region Initializes Server and Client based on specific protocol sequence this.authenticationLevel = (uint)Convert.ToInt32(Common.GetConfigurationPropertyValue("RpcAuthenticationLevel", this.Site)); this.authenticationService = (uint)Convert.ToInt32(Common.GetConfigurationPropertyValue("RPCAuthenticationService", this.Site)); #endregion } } /// <summary> /// Clean up the test case after running it /// </summary> protected override void TestCleanup() { if (!this.transportIsMAPI) { this.HardDeleteMessagesAndSubfolders(FolderIds.Inbox); this.HardDeleteMessagesAndSubfolders(FolderIds.SentItems); } base.TestCleanup(); } #endregion #region Private Methods /// <summary> /// Hard delete messages and subfolders under the specified folder. /// </summary> /// <param name="folderIndex">The id of folder in which subfolders and messages should be deleted</param> protected void HardDeleteMessagesAndSubfolders(FolderIds folderIndex) { #region Client connects with Server this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed. This call is the precondition for EcDoRpcExt2. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Logon to mailbox this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, "RopLogon should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopLogonResponse logonResponse = (RopLogonResponse)this.response; uint logonHandle = this.responseSOHTable[TestSuiteBase.FIRST][logonResponse.OutputHandleIndex]; #endregion #region OpenFolder this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopOpenFolder, logonHandle, logonResponse.FolderIds[(int)folderIndex]); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.responseSOHTable = new List<List<uint>>(); uint payloadCount = 0; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoXorMagic, this.rgbIn, ref this.rgbOut, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable, out payloadCount, ref this.rgbAuxOut); Site.Assert.AreEqual<uint>(0, this.returnValue, "RopOpenFolder should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopOpenFolderResponse openFolderResponse = (RopOpenFolderResponse)this.response; this.objHandle = this.responseSOHTable[TestSuiteBase.FIRST][openFolderResponse.OutputHandleIndex]; #endregion #region HardDeleteFoldersAndMessages this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopHardDeleteMessagesAndSubfolders, this.objHandle, 0); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.responseSOHTable = new List<List<uint>>(); payloadCount = 0; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoXorMagic, this.rgbIn, ref this.rgbOut, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable, out payloadCount, ref this.rgbAuxOut); // The returned value 1125 means ecNoDelSubmitMsg, that is, deleting a message that has been submitted for sending is not permitted. bool retValue = (this.returnValue == 0) || (this.returnValue == 1125); Site.Assert.AreEqual<bool>(true, retValue, "The returned status is {0}. TRUE means that RopHardDeleteMessagesAndSubfolders succeed, and FALSE means that RopHardDeleteMessagesAndSubfolders failed.", retValue); #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoDisconnect should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion } /// <summary> /// Check the transport. If the transport is MAPI HTTP, issue the inconclusive status. /// </summary> protected void CheckTransport() { if (this.transportIsMAPI) { Site.Assume.Inconclusive("MS-OXCRPC doesn't support MS-OXCMAPIHTTP."); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Buffers.Text { public static partial class Utf8Parser { // // Roundtrippable format. One of // // 012345678901234567890123456789012 // --------------------------------- // 2017-06-12T05:30:45.7680000-07:00 // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local) // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone) // private static bool TryParseDateTimeOffsetO(ReadOnlySpan<byte> source, out DateTimeOffset value, out int bytesConsumed, out DateTimeKind kind) { if (source.Length < 27) { value = default; bytesConsumed = 0; kind = default; return false; } int year; { uint digit1 = source[0] - 48u; // '0' uint digit2 = source[1] - 48u; // '0' uint digit3 = source[2] - 48u; // '0' uint digit4 = source[3] - 48u; // '0' if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } year = (int)(digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4); } if (source[4] != Utf8Constants.Hyphen) { value = default; bytesConsumed = 0; kind = default; return false; } int month; { uint digit1 = source[5] - 48u; // '0' uint digit2 = source[6] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } month = (int)(digit1 * 10 + digit2); } if (source[7] != Utf8Constants.Hyphen) { value = default; bytesConsumed = 0; kind = default; return false; } int day; { uint digit1 = source[8] - 48u; // '0' uint digit2 = source[9] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } day = (int)(digit1 * 10 + digit2); } if (source[10] != 'T') { value = default; bytesConsumed = 0; kind = default; return false; } int hour; { uint digit1 = source[11] - 48u; // '0' uint digit2 = source[12] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } hour = (int)(digit1 * 10 + digit2); } if (source[13] != Utf8Constants.Colon) { value = default; bytesConsumed = 0; kind = default; return false; } int minute; { uint digit1 = source[14] - 48u; // '0' uint digit2 = source[15] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } minute = (int)(digit1 * 10 + digit2); } if (source[16] != Utf8Constants.Colon) { value = default; bytesConsumed = 0; kind = default; return false; } int second; { uint digit1 = source[17] - 48u; // '0' uint digit2 = source[18] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } second = (int)(digit1 * 10 + digit2); } if (source[19] != Utf8Constants.Period) { value = default; bytesConsumed = 0; kind = default; return false; } int fraction; { uint digit1 = source[20] - 48u; // '0' uint digit2 = source[21] - 48u; // '0' uint digit3 = source[22] - 48u; // '0' uint digit4 = source[23] - 48u; // '0' uint digit5 = source[24] - 48u; // '0' uint digit6 = source[25] - 48u; // '0' uint digit7 = source[26] - 48u; // '0' if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9 || digit5 > 9 || digit6 > 9 || digit7 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } fraction = (int)(digit1 * 1000000 + digit2 * 100000 + digit3 * 10000 + digit4 * 1000 + digit5 * 100 + digit6 * 10 + digit7); } byte offsetChar = (source.Length <= 27) ? default : source[27]; if (offsetChar != 'Z' && offsetChar != Utf8Constants.Plus && offsetChar != Utf8Constants.Minus) { if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, out value)) { value = default; bytesConsumed = 0; kind = default; return false; } bytesConsumed = 27; kind = DateTimeKind.Unspecified; return true; } if (offsetChar == 'Z') { // Same as specifying an offset of "+00:00", except that DateTime's Kind gets set to UTC rather than Local if (!TryCreateDateTimeOffset(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, offsetNegative: false, offsetHours: 0, offsetMinutes: 0, out value)) { value = default; bytesConsumed = 0; kind = default; return false; } bytesConsumed = 28; kind = DateTimeKind.Utc; return true; } Debug.Assert(offsetChar == Utf8Constants.Plus || offsetChar == Utf8Constants.Minus); if (source.Length < 33) { value = default; bytesConsumed = 0; kind = default; return false; } int offsetHours; { uint digit1 = source[28] - 48u; // '0' uint digit2 = source[29] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } offsetHours = (int)(digit1 * 10 + digit2); } if (source[30] != Utf8Constants.Colon) { value = default; bytesConsumed = 0; kind = default; return false; } int offsetMinutes; { uint digit1 = source[31] - 48u; // '0' uint digit2 = source[32] - 48u; // '0' if (digit1 > 9 || digit2 > 9) { value = default; bytesConsumed = 0; kind = default; return false; } offsetMinutes = (int)(digit1 * 10 + digit2); } if (!TryCreateDateTimeOffset(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, offsetNegative: offsetChar == Utf8Constants.Minus, offsetHours: offsetHours, offsetMinutes: offsetMinutes, out value)) { value = default; bytesConsumed = 0; kind = default; return false; } bytesConsumed = 33; kind = DateTimeKind.Local; return true; } } }
/* * * (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.Configuration; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Users; using ASC.Web.Core; using ASC.Web.Core.WhiteLabel; using ASC.Web.Studio.Core; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.UserControls.Statistics; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.Management { [AjaxNamespace("TariffNotifyController")] public partial class TariffNotify : UserControl { public static string Location { get { return "~/UserControls/Management/TariffSettings/TariffNotify.ascx"; } } protected Tuple<string, string> Notify = null; protected bool CanClose = false; protected void Page_Load(object sender, EventArgs e) { if (CoreContext.Configuration.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace")) { Notify = GetPersonalTariffNotify(); return; } if (SecurityContext.IsAuthenticated && TenantExtra.EnableTariffSettings && !TariffSettings.HideNotify && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { Page.RegisterStyle("~/UserControls/Management/TariffSettings/css/tariffnotify.less"); Notify = GetTariffNotify(); if (CanClose) { Page.RegisterBodyScripts("~/UserControls/Management/TariffSettings/js/tariffnotify.js"); AjaxPro.Utility.RegisterTypeForAjax(GetType()); } } } private Tuple<string, string> GetPersonalTariffNotify() { var maxTotalSize = CoreContext.Configuration.PersonalMaxSpace; var webItem = WebItemManager.Instance[WebItemManager.DocumentsProductID]; var spaceUsageManager = webItem.Context.SpaceUsageStatManager as IUserSpaceUsage; if (spaceUsageManager == null) return null; var usedSize = spaceUsageManager.GetUserSpaceUsage(SecurityContext.CurrentAccount.ID); long notifySize; long.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.storage"] ?? "104857600", out notifySize); //100 MB if (notifySize > 0 && maxTotalSize - usedSize < notifySize) { var head = string.Format(Resource.PersonalTariffExceedLimit, FileSizeComment.FilesSizeToString(maxTotalSize)); string text; if (CoreContext.Configuration.CustomMode) { text = string.Format(Resource.PersonalTariffExceedLimitInfoText, string.Empty, string.Empty, "</br>"); } else { var settings = MailWhiteLabelSettings.Instance; var supportLink = string.Format("<a target=\"_blank\" href=\"{0}\">", settings.SupportUrl); text = string.Format(Resource.PersonalTariffExceedLimitInfoText, supportLink, "</a>", "</br>"); } return new Tuple<string, string>(head, text); } return null; } private Tuple<string, string> GetTariffNotify() { var hidePricingPage = !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin() && TariffSettings.HidePricingPage; var tariff = TenantExtra.GetCurrentTariff(); var count = tariff.DueDate.Date.Subtract(DateTime.Today).Days; if (tariff.State == TariffState.Trial) { if (!hidePricingPage && count <= 5) { var text = String.Format(CoreContext.Configuration.Standalone ? Resource.TariffLinkStandalone : Resource.TrialPeriodInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) return new Tuple<string, string>(Resource.TrialPeriodExpired, text); var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return new Tuple<string, string>(string.Format(Resource.TrialPeriod, count, end), text); } if (CoreContext.Configuration.Standalone) { return new Tuple<string, string>(Resource.TrialPeriodInfoTextLicense, string.Empty); } } if (!hidePricingPage && tariff.State == TariffState.Paid) { if (CoreContext.Configuration.Standalone) { CanClose = true; var text = String.Format(Resource.TariffLinkStandaloneLife, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) return new Tuple<string, string>(Resource.PaidPeriodExpiredStandaloneLife, text); if (count < 10) { var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return new Tuple<string, string>(string.Format(Resource.PaidPeriodStandaloneLife, count, end), text); } } else { var quota = TenantExtra.GetTenantQuota(); long notifySize; long.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize) { var head = string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize)); var text = String.Format(Resource.TariffExceedLimitInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); return new Tuple<string, string>(head, text); } } } if (!hidePricingPage && tariff.State == TariffState.Delay) { var text = String.Format(Resource.TariffPaymentDelayText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>", tariff.DelayDueDate.Date.ToLongDateString()); return new Tuple<string, string>(Resource.TariffPaymentDelay, text); } return null; } public static string GetNumeralResourceByCount(int count, string resource, string resourceOne, string resourceTwo) { var num = count % 100; if (num >= 11 && num <= 19) { return resourceTwo; } var i = count % 10; switch (i) { case (1): return resource; case (2): case (3): case (4): return resourceOne; default: return resourceTwo; } } [AjaxMethod] public void HideNotify() { TariffSettings.HideNotify = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Specifies what kind of jump this <see cref="GotoExpression"/> represents. /// </summary> public enum GotoExpressionKind { /// <summary> /// A <see cref="GotoExpression"/> that represents a jump to some location. /// </summary> Goto, /// <summary> /// A <see cref="GotoExpression"/> that represents a return statement. /// </summary> Return, /// <summary> /// A <see cref="GotoExpression"/> that represents a break statement. /// </summary> Break, /// <summary> /// A <see cref="GotoExpression"/> that represents a continue statement. /// </summary> Continue, } /// <summary> /// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps. /// </summary> [DebuggerTypeProxy(typeof(Expression.GotoExpressionProxy))] public sealed class GotoExpression : Expression { private readonly GotoExpressionKind _kind; private readonly Expression _value; private readonly LabelTarget _target; private readonly Type _type; internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { _kind = kind; _value = value; _target = target; _type = type; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Goto; } } /// <summary> /// The value passed to the target, or null if the target is of type /// System.Void. /// </summary> public Expression Value { get { return _value; } } /// <summary> /// The target label where this node jumps to. /// </summary> public LabelTarget Target { get { return _target; } } /// <summary> /// The kind of the goto. For information purposes only. /// </summary> public GotoExpressionKind Kind { get { return _kind; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitGoto(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="target">The <see cref="Target" /> property of the result.</param> /// <param name="value">The <see cref="Value" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public GotoExpression Update(LabelTarget target, Expression value) { if (target == Target && value == Value) { return this; } return Expression.MakeGoto(Kind, target, value, Type); } } public partial class Expression { /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target) { return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>. /// </returns> public static GotoExpression Break(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Break, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Break, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target) { return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Continue, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target) { return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Return, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Return, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target) { return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>. /// The value passed to the label upon jumping can also be specified. /// </summary> /// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to <paramref name="kind"/>, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { ValidateGoto(target, ref value, nameof(target), nameof(value)); return new GotoExpression(kind, target, value, type); } private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter) { ContractUtils.RequiresNotNull(target, targetParameter); if (value == null) { if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(nameof(target)); } else { ValidateGotoType(target.Type, ref value, valueParameter); } } // Standard argument validation, taken from ValidateArgumentTypes private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName) { RequiresCanRead(value, paramName); if (expectedType != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type)) { // C# auto-quotes return values, so we'll do that here if (!TryQuote(expectedType, ref value)) { throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType); } } } } } }
/* JSONObject.cs -- Simple C# JSON parser version 1.4 - March 17, 2014 Copyright (C) 2012 Boomlagoon Ltd. contact@boomlagoon.com */ #define PARSE_ESCAPED_UNICODE #if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH #define USE_UNITY_DEBUGGING #endif using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; #if PARSE_ESCAPED_UNICODE using System.Text.RegularExpressions; #endif #if USE_UNITY_DEBUGGING using UnityEngine; #else using System.Diagnostics; #endif namespace Boomlagoon.JSON { public static class Extensions { public static T Pop<T>(this List<T> list) { var result = list[list.Count - 1]; list.RemoveAt(list.Count - 1); return result; } } static class JSONLogger { #if USE_UNITY_DEBUGGING public static void Log(string str) { Debug.Log(str); } public static void Error(string str) { Debug.LogError(str); } #else public static void Log(string str) { Debug.WriteLine(str); } public static void Error(string str) { Debug.WriteLine(str); } #endif } public enum JSONValueType { String, Number, Object, Array, Boolean, Null } public class JSONValue { public JSONValue(JSONValueType type) { Type = type; } public JSONValue(string str) { Type = JSONValueType.String; Str = str; } public JSONValue(double number) { Type = JSONValueType.Number; Number = number; } public JSONValue(JSONObject obj) { if (obj == null) { Type = JSONValueType.Null; } else { Type = JSONValueType.Object; Obj = obj; } } public JSONValue(JSONArray array) { Type = JSONValueType.Array; Array = array; } public JSONValue(bool boolean) { Type = JSONValueType.Boolean; Boolean = boolean; } /// <summary> /// Construct a copy of the JSONValue given as a parameter /// </summary> /// <param name="value"></param> public JSONValue(JSONValue value) { Type = value.Type; switch (Type) { case JSONValueType.String: Str = value.Str; break; case JSONValueType.Boolean: Boolean = value.Boolean; break; case JSONValueType.Number: Number = value.Number; break; case JSONValueType.Object: if (value.Obj != null) { Obj = new JSONObject(value.Obj); } break; case JSONValueType.Array: Array = new JSONArray(value.Array); break; } } public JSONValueType Type { get; private set; } public string Str { get; set; } public double Number { get; set; } public JSONObject Obj { get; set; } public JSONArray Array { get; set; } public bool Boolean { get; set; } public JSONValue Parent { get; set; } public static implicit operator JSONValue(string str) { return new JSONValue(str); } public static implicit operator JSONValue(double number) { return new JSONValue(number); } public static implicit operator JSONValue(JSONObject obj) { return new JSONValue(obj); } public static implicit operator JSONValue(JSONArray array) { return new JSONValue(array); } public static implicit operator JSONValue(bool boolean) { return new JSONValue(boolean); } /// <returns>String representation of this JSONValue</returns> public override string ToString() { switch (Type) { case JSONValueType.Object: return Obj.ToString(); case JSONValueType.Array: return Array.ToString(); case JSONValueType.Boolean: return Boolean ? "true" : "false"; case JSONValueType.Number: return Number.ToString(); case JSONValueType.String: return "\"" + Str + "\""; case JSONValueType.Null: return "null"; } return "null"; } } public class JSONArray : IEnumerable<JSONValue> { private readonly List<JSONValue> values = new List<JSONValue>(); public JSONArray() { } /// <summary> /// Construct a new array and copy each value from the given array into the new one /// </summary> /// <param name="array"></param> public JSONArray(JSONArray array) { values = new List<JSONValue>(); foreach (var v in array.values) { values.Add(new JSONValue(v)); } } /// <summary> /// Add a JSONValue to this array /// </summary> /// <param name="value"></param> public void Add(JSONValue value) { values.Add(value); } public JSONValue this[int index] { get { return values[index]; } set { values[index] = value; } } /// <returns> /// Return the length of the array /// </returns> public int Length { get { return values.Count; } } /// <returns>String representation of this JSONArray</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append('['); foreach (var value in values) { stringBuilder.Append(value.ToString()); stringBuilder.Append(','); } if (values.Count > 0) { stringBuilder.Remove(stringBuilder.Length - 1, 1); } stringBuilder.Append(']'); return stringBuilder.ToString(); } public IEnumerator<JSONValue> GetEnumerator() { return values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } /// <summary> /// Attempt to parse a string as a JSON array. /// </summary> /// <param name="jsonString"></param> /// <returns>A new JSONArray object if successful, null otherwise.</returns> public static JSONArray Parse(string jsonString) { var tempObject = JSONObject.Parse("{ \"array\" :" + jsonString + '}'); return tempObject == null ? null : tempObject.GetValue("array").Array; } /// <summary> /// Empty the array of all values. /// </summary> public void Clear() { values.Clear(); } /// <summary> /// Remove the value at the given index, if it exists. /// </summary> /// <param name="index"></param> public void Remove(int index) { if (index >= 0 && index < values.Count) { values.RemoveAt(index); } else { JSONLogger.Error("index out of range: " + index + " (Expected 0 <= index < " + values.Count + ")"); } } /// <summary> /// Concatenate two JSONArrays /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns>A new JSONArray that is the result of adding all of the right-hand side array's values to the left-hand side array.</returns> public static JSONArray operator +(JSONArray lhs, JSONArray rhs) { var result = new JSONArray(lhs); foreach (var value in rhs.values) { result.Add(value); } return result; } } public class JSONObject : IEnumerable<KeyValuePair<string, JSONValue>> { private enum JSONParsingState { Object, Array, EndObject, EndArray, Key, Value, KeyValueSeparator, ValueSeparator, String, Number, Boolean, Null } private readonly IDictionary<string, JSONValue> values = new Dictionary<string, JSONValue>(); #if PARSE_ESCAPED_UNICODE private static readonly Regex unicodeRegex = new Regex(@"\\u([0-9a-fA-F]{4})"); private static readonly byte[] unicodeBytes = new byte[2]; #endif public JSONObject() { } /// <summary> /// Construct a copy of the given JSONObject. /// </summary> /// <param name="other"></param> public JSONObject(JSONObject other) { values = new Dictionary<string, JSONValue>(); if (other != null) { foreach (var keyValuePair in other.values) { values[keyValuePair.Key] = new JSONValue(keyValuePair.Value); } } } /// <param name="key"></param> /// <returns>Does 'key' exist in this object.</returns> public bool ContainsKey(string key) { return values.ContainsKey(key); } public JSONValue GetValue(string key) { JSONValue value; values.TryGetValue(key, out value); return value; } public string GetString(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + "(string) == null"); return string.Empty; } return value.Str; } public double GetNumber(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return double.NaN; } return value.Number; } public JSONObject GetObject(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return null; } return value.Obj; } public bool GetBoolean(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return false; } return value.Boolean; } public JSONArray GetArray(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return null; } return value.Array; } public JSONValue this[string key] { get { return GetValue(key); } set { values[key] = value; } } public void Add(string key, JSONValue value) { values[key] = value; } public void Add(KeyValuePair<string, JSONValue> pair) { values[pair.Key] = pair.Value; } /// <summary> /// Attempt to parse a string into a JSONObject. /// </summary> /// <param name="jsonString"></param> /// <returns>A new JSONObject or null if parsing fails.</returns> public static JSONObject Parse(string jsonString) { if (string.IsNullOrEmpty(jsonString)) { return null; } JSONValue currentValue = null; var keyList = new List<string>(); var state = JSONParsingState.Object; for (var startPosition = 0; startPosition < jsonString.Length; ++startPosition) { startPosition = SkipWhitespace(jsonString, startPosition); switch (state) { case JSONParsingState.Object: if (jsonString[startPosition] != '{') { return Fail('{', startPosition); } JSONValue newObj = new JSONObject(); if (currentValue != null) { newObj.Parent = currentValue; } currentValue = newObj; state = JSONParsingState.Key; break; case JSONParsingState.EndObject: if (jsonString[startPosition] != '}') { return Fail('}', startPosition); } if (currentValue.Parent == null) { return currentValue.Obj; } switch (currentValue.Parent.Type) { case JSONValueType.Object: currentValue.Parent.Obj.values[keyList.Pop()] = new JSONValue(currentValue.Obj); break; case JSONValueType.Array: currentValue.Parent.Array.Add(new JSONValue(currentValue.Obj)); break; default: return Fail("valid object", startPosition); } currentValue = currentValue.Parent; state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Key: if (jsonString[startPosition] == '}') { --startPosition; state = JSONParsingState.EndObject; break; } var key = ParseString(jsonString, ref startPosition); if (key == null) { return Fail("key string", startPosition); } keyList.Add(key); state = JSONParsingState.KeyValueSeparator; break; case JSONParsingState.KeyValueSeparator: if (jsonString[startPosition] != ':') { return Fail(':', startPosition); } state = JSONParsingState.Value; break; case JSONParsingState.ValueSeparator: switch (jsonString[startPosition]) { case ',': state = currentValue.Type == JSONValueType.Object ? JSONParsingState.Key : JSONParsingState.Value; break; case '}': state = JSONParsingState.EndObject; --startPosition; break; case ']': state = JSONParsingState.EndArray; --startPosition; break; default: return Fail(", } ]", startPosition); } break; case JSONParsingState.Value: { var c = jsonString[startPosition]; if (c == '"') { state = JSONParsingState.String; } else if (char.IsDigit(c) || c == '-') { state = JSONParsingState.Number; } else switch (c) { case '{': state = JSONParsingState.Object; break; case '[': state = JSONParsingState.Array; break; case ']': if (currentValue.Type == JSONValueType.Array) { state = JSONParsingState.EndArray; } else { return Fail("valid array", startPosition); } break; case 'f': case 't': state = JSONParsingState.Boolean; break; case 'n': state = JSONParsingState.Null; break; default: return Fail("beginning of value", startPosition); } --startPosition; //To re-evaluate this char in the newly selected state break; } case JSONParsingState.String: var str = ParseString(jsonString, ref startPosition); if (str == null) { return Fail("string value", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(str); break; case JSONValueType.Array: currentValue.Array.Add(str); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Number: var number = ParseNumber(jsonString, ref startPosition); if (double.IsNaN(number)) { return Fail("valid number", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(number); break; case JSONValueType.Array: currentValue.Array.Add(number); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Boolean: if (jsonString[startPosition] == 't') { if (jsonString.Length < startPosition + 4 || jsonString[startPosition + 1] != 'r' || jsonString[startPosition + 2] != 'u' || jsonString[startPosition + 3] != 'e') { return Fail("true", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(true); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(true)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 3; } else { if (jsonString.Length < startPosition + 5 || jsonString[startPosition + 1] != 'a' || jsonString[startPosition + 2] != 'l' || jsonString[startPosition + 3] != 's' || jsonString[startPosition + 4] != 'e') { return Fail("false", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(false); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(false)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 4; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Array: if (jsonString[startPosition] != '[') { return Fail('[', startPosition); } JSONValue newArray = new JSONArray(); if (currentValue != null) { newArray.Parent = currentValue; } currentValue = newArray; state = JSONParsingState.Value; break; case JSONParsingState.EndArray: if (jsonString[startPosition] != ']') { return Fail(']', startPosition); } if (currentValue.Parent == null) { return currentValue.Obj; } switch (currentValue.Parent.Type) { case JSONValueType.Object: currentValue.Parent.Obj.values[keyList.Pop()] = new JSONValue(currentValue.Array); break; case JSONValueType.Array: currentValue.Parent.Array.Add(new JSONValue(currentValue.Array)); break; default: return Fail("valid object", startPosition); } currentValue = currentValue.Parent; state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Null: if (jsonString[startPosition] == 'n') { if (jsonString.Length < startPosition + 4 || jsonString[startPosition + 1] != 'u' || jsonString[startPosition + 2] != 'l' || jsonString[startPosition + 3] != 'l') { return Fail("null", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(JSONValueType.Null); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(JSONValueType.Null)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 3; } state = JSONParsingState.ValueSeparator; break; } } JSONLogger.Error("Unexpected end of string"); return null; } private static int SkipWhitespace(string str, int pos) { for (; pos < str.Length && char.IsWhiteSpace(str[pos]); ++pos) ; return pos; } private static string ParseString(string str, ref int startPosition) { if (str[startPosition] != '"' || startPosition + 1 >= str.Length) { Fail('"', startPosition); return null; } var endPosition = str.IndexOf('"', startPosition + 1); if (endPosition <= startPosition) { Fail('"', startPosition + 1); return null; } while (str[endPosition - 1] == '\\') { endPosition = str.IndexOf('"', endPosition + 1); if (endPosition <= startPosition) { Fail('"', startPosition + 1); return null; } } var result = string.Empty; if (endPosition > startPosition + 1) { result = str.Substring(startPosition + 1, endPosition - startPosition - 1); } startPosition = endPosition; #if PARSE_ESCAPED_UNICODE // Parse Unicode characters that are escaped as \uXXXX do { Match m = unicodeRegex.Match(result); if (!m.Success) { break; } string s = m.Groups[1].Captures[0].Value; unicodeBytes[1] = byte.Parse(s.Substring(0, 2), NumberStyles.HexNumber); unicodeBytes[0] = byte.Parse(s.Substring(2, 2), NumberStyles.HexNumber); s = Encoding.Unicode.GetString(unicodeBytes); result = result.Replace(m.Value, s); } while (true); #endif return result; } private static double ParseNumber(string str, ref int startPosition) { if (startPosition >= str.Length || (!char.IsDigit(str[startPosition]) && str[startPosition] != '-')) { return double.NaN; } var endPosition = startPosition + 1; for (; endPosition < str.Length && str[endPosition] != ',' && str[endPosition] != ']' && str[endPosition] != '}'; ++endPosition) ; double result; if ( !double.TryParse(str.Substring(startPosition, endPosition - startPosition), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result)) { return double.NaN; } startPosition = endPosition - 1; return result; } private static JSONObject Fail(char expected, int position) { return Fail(new string(expected, 1), position); } private static JSONObject Fail(string expected, int position) { JSONLogger.Error("Invalid json string, expecting " + expected + " at " + position); return null; } /// <returns>String representation of this JSONObject</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append('{'); foreach (var pair in values) { stringBuilder.Append("\"" + pair.Key + "\""); stringBuilder.Append(':'); stringBuilder.Append(pair.Value.ToString()); stringBuilder.Append(','); } if (values.Count > 0) { stringBuilder.Remove(stringBuilder.Length - 1, 1); } stringBuilder.Append('}'); return stringBuilder.ToString(); } public IEnumerator<KeyValuePair<string, JSONValue>> GetEnumerator() { return values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } /// <summary> /// Empty this JSONObject of all values. /// </summary> public void Clear() { values.Clear(); } /// <summary> /// Remove the JSONValue attached to the given key. /// </summary> /// <param name="key"></param> public void Remove(string key) { if (values.ContainsKey(key)) { values.Remove(key); } } } }
#region Apache License // // 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. // #endregion using System; using System.Xml; using System.Collections; using System.IO; using System.Reflection; using System.Threading; using System.Net; using log4net.Appender; using log4net.Util; using log4net.Repository; namespace log4net.Config { /// <summary> /// Use this class to initialize the log4net environment using an Xml tree. /// </summary> /// <remarks> /// <para> /// Configures a <see cref="ILoggerRepository"/> using an Xml tree. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class XmlConfigurator { #region Private Instance Constructors /// <summary> /// Private constructor /// </summary> private XmlConfigurator() { } #endregion Protected Instance Constructors #region Configure static methods /// <summary> /// utility property to get the difference between NEMF assemblies and big assemblies /// </summary> private static Assembly CallingAssembly { #if !NETMF get { return Assembly.GetCallingAssembly(); } #else get { return Assembly.GetExecutingAssembly(); } #endif } #if !NETCF && !NETMF /// <summary> /// Automatically configures the log4net system based on the /// application's configuration settings. /// </summary> /// <remarks> /// <para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </para> /// <para> /// To use this method to configure log4net you must specify /// the <see cref="Log4NetConfigurationSectionHandler"/> section /// handler for the <c>log4net</c> configuration section. See the /// <see cref="Log4NetConfigurationSectionHandler"/> for an example. /// </para> /// </remarks> /// <seealso cref="Log4NetConfigurationSectionHandler"/> #else /// <summary> /// Automatically configures the log4net system based on the /// application's configuration settings. /// </summary> /// <remarks> /// <para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </para> /// </remarks> #endif static public ICollection Configure() { return Configure(LogManager.GetRepository(CallingAssembly)); } #if !NETCF && !NETMF /// <summary> /// Automatically configures the <see cref="ILoggerRepository"/> using settings /// stored in the application's configuration file. /// </summary> /// <remarks> /// <para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </para> /// <para> /// To use this method to configure log4net you must specify /// the <see cref="Log4NetConfigurationSectionHandler"/> section /// handler for the <c>log4net</c> configuration section. See the /// <see cref="Log4NetConfigurationSectionHandler"/> for an example. /// </para> /// </remarks> /// <param name="repository">The repository to configure.</param> #else /// <summary> /// Automatically configures the <see cref="ILoggerRepository"/> using settings /// stored in the application's configuration file. /// </summary> /// <remarks> /// <para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </para> /// </remarks> /// <param name="repository">The repository to configure.</param> #endif static public ICollection Configure(ILoggerRepository repository) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } static private void InternalConfigure(ILoggerRepository repository) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section"); try { LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]"); } catch { // ignore error LogLog.Debug(declaringType, "Application config file location unknown"); } #if NETCF || NETMF // No config file reading stuff. Just go straight for the file Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation)); #else try { XmlElement configElement = null; #if NET_2_0 configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement; #else configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement; #endif if (configElement == null) { // Failed to load the xml config using configuration settings handler LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />"); } else { // Configure using the xml loaded from the config file InternalConfigureFromXml(repository, configElement); } } catch(System.Configuration.ConfigurationException confEx) { if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0) { // Looks like the XML file is not valid LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx); } else { // This exception is typically due to the assembly name not being correctly specified in the section type. string configSectionStr = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />"; LogLog.Error(declaringType, "Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx); } } #endif } #if !NETMF /// <summary> /// Configures log4net using a <c>log4net</c> element /// </summary> /// <remarks> /// <para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </para> /// </remarks> /// <param name="element">The element to parse.</param> static public ICollection Configure(XmlElement element) { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(CallingAssembly); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigureFromXml(repository, element); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } #endif #if !NETMF /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified XML /// element. /// </summary> /// <remarks> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </remarks> /// <param name="repository">The repository to configure.</param> /// <param name="element">The element to parse.</param> static public ICollection Configure(ILoggerRepository repository, XmlElement element) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element"); InternalConfigureFromXml(repository, element); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } #endif #if !NETCF && !NETMF /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <para> /// The first element matching <c>&lt;configuration&gt;</c> will be read as the /// configuration. If this file is also a .NET .config file then you must specify /// a configuration section for the <c>log4net</c> element otherwise .NET will /// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example: /// <code lang="XML" escaped="true"> /// <configSections> /// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> /// </configSections> /// </code> /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> #else /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> #endif static public ICollection Configure(FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(LogManager.GetRepository(CallingAssembly), configFile); } return configurationMessages; } /// <summary> /// Configures log4net using the specified configuration URI. /// </summary> /// <param name="configUri">A URI to load the XML configuration from.</param> /// <remarks> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified. /// </para> /// </remarks> static public ICollection Configure(Uri configUri) { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(CallingAssembly); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository, configUri); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } /// <summary> /// Configures log4net using the specified configuration data stream. /// </summary> /// <param name="configStream">A stream to load the XML configuration from.</param> /// <remarks> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> static public ICollection Configure(Stream configStream) { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(CallingAssembly); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository, configStream); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } #if !NETCF /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <para> /// The first element matching <c>&lt;configuration&gt;</c> will be read as the /// configuration. If this file is also a .NET .config file then you must specify /// a configuration section for the <c>log4net</c> element otherwise .NET will /// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example: /// <code lang="XML" escaped="true"> /// <configSections> /// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> /// </configSections> /// </code> /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> #else /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> #endif static public ICollection Configure(ILoggerRepository repository, FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository, configFile); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } static private void InternalConfigure(ILoggerRepository repository, FileInfo configFile) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]"); if (configFile == null) { LogLog.Error(declaringType, "Configure called with null 'configFile' parameter"); } else { // Have to use File.Exists() rather than configFile.Exists() // because configFile.Exists() caches the value, not what we want. if (File.Exists(configFile.FullName)) { // Open the file for reading FileStream fs = null; // Try hard to open the file for(int retry = 5; --retry >= 0; ) { try { #if NETMF fs = File.OpenRead(configFile.FullName); #else fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); #endif break; } catch(IOException ex) { if (retry == 0) { LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex); // The stream cannot be valid fs = null; } System.Threading.Thread.Sleep(250); } } if (fs != null) { try { // Load the configuration from the stream InternalConfigure(repository, fs); } finally { // Force the file closed whatever happens fs.Close(); } } } else { LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged."); } } } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// URI. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configUri">A URI to load the XML configuration from.</param> /// <remarks> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified. /// </para> /// </remarks> static public ICollection Configure(ILoggerRepository repository, Uri configUri) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository, configUri); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } static private void InternalConfigure(ILoggerRepository repository, Uri configUri) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]"); if (configUri == null) { LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); } else { #if !NETMF if (configUri.IsFile) { // If URI is local file then call Configure with FileInfo InternalConfigure(repository, new FileInfo(configUri.LocalPath)); } else #endif { // NETCF dose not support WebClient WebRequest configRequest = null; try { configRequest = WebRequest.Create(configUri); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex); } if (configRequest != null) { #if !NETCF_1_0 && !NETMF // authentication may be required, set client to use default credentials try { configRequest.Credentials = CredentialCache.DefaultCredentials; } catch { // ignore security exception } #endif try { WebResponse response = configRequest.GetResponse(); if (response != null) { try { // Open stream on config URI using(Stream configStream = response.GetResponseStream()) { InternalConfigure(repository, configStream); } } finally { response.Close(); } } } catch(Exception ex) { LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex); } } } } } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configStream">The stream to load the XML configuration from.</param> /// <remarks> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> static public ICollection Configure(ILoggerRepository repository, Stream configStream) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigure(repository, configStream); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } static private void InternalConfigure(ILoggerRepository repository, Stream configStream) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); if (configStream == null) { LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); } else { // Load the config file into a document /// \todo This is all horribly wrong on NETMF - there ISN'T an XmlDocument so you need to read the config the old fashioned way XmlDocument doc = new XmlDocument(); try { #if NETCF || NETMF // Create a text reader for the file stream XmlTextReader xmlReader = new XmlTextReader(configStream); // Test code - see how we read XML using the #elif NET_2_0 // Allow the DTD to specify entity includes XmlReaderSettings settings = new XmlReaderSettings(); // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd' // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.' #if !NET_4_0 settings.ProhibitDtd = false; #else settings.DtdProcessing = DtdProcessing.Parse; #endif // Create a reader over the input stream XmlReader xmlReader = XmlReader.Create(configStream, settings); #else // Create a validating reader around a text reader for the file stream XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream)); // Specify that the reader should not perform validation, but that it should // expand entity refs. xmlReader.ValidationType = ValidationType.None; xmlReader.EntityHandling = EntityHandling.ExpandEntities; #endif // load the data into the document doc.Load(xmlReader); } catch(Exception ex) { LogLog.Error(declaringType, "Error while loading XML configuration", ex); // The document is invalid doc = null; } if (doc != null) { LogLog.Debug(declaringType, "loading XML configuration"); // Configure using the 'log4net' element XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); if (configNodeList.Count == 0) { LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted."); } else if (configNodeList.Count > 1) { LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted."); } else { InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); } } } } #endregion Configure static methods #region ConfigureAndWatch static methods #if (!NETCF && !SSCLI) /// <summary> /// Configures log4net using the file specified, monitors the file for changes /// and reloads the configuration if a change is detected. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="M:Configure(FileInfo)"/> static public ICollection ConfigureAndWatch(FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(CallingAssembly); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigureAndWatch(repository, configFile); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the file specified, /// monitors the file for changes and reloads the configuration if a change /// is detected. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="M:Configure(FileInfo)"/> static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { InternalConfigureAndWatch(repository, configFile); } repository.ConfigurationMessages = configurationMessages; return configurationMessages; } static private void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates"); if (configFile == null) { LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter"); } else { // Configure log4net now InternalConfigure(repository, configFile); try { lock (m_repositoryName2ConfigAndWatchHandler) { // support multiple repositories each having their own watcher ConfigureAndWatchHandler handler = (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName]; if (handler != null) { m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName); handler.Dispose(); } // Create and start a watch handler that will reload the // configuration whenever the config file is modified. handler = new ConfigureAndWatchHandler(repository, configFile); m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler; } } catch(Exception ex) { LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex); } } } #endif #endregion ConfigureAndWatch static methods #region ConfigureAndWatchHandler #if (!NETCF && !SSCLI && !NETMF) /// <summary> /// Class used to watch config files. /// </summary> /// <remarks> /// <para> /// Uses the <see cref="FileSystemWatcher"/> to monitor /// changes to a specified file. Because multiple change notifications /// may be raised when the file is modified, a timer is used to /// compress the notifications into a single event. The timer /// waits for <see cref="TimeoutMillis"/> time before delivering /// the event notification. If any further <see cref="FileSystemWatcher"/> /// change notifications arrive while the timer is waiting it /// is reset and waits again for <see cref="TimeoutMillis"/> to /// elapse. /// </para> /// </remarks> private sealed class ConfigureAndWatchHandler : IDisposable { /// <summary> /// Holds the FileInfo used to configure the XmlConfigurator /// </summary> private FileInfo m_configFile; /// <summary> /// Holds the repository being configured. /// </summary> private ILoggerRepository m_repository; /// <summary> /// The timer used to compress the notification events. /// </summary> private Timer m_timer; /// <summary> /// The default amount of time to wait after receiving notification /// before reloading the config file. /// </summary> private const int TimeoutMillis = 500; /// <summary> /// Watches file for changes. This object should be disposed when no longer /// needed to free system handles on the watched resources. /// </summary> private FileSystemWatcher m_watcher; /// <summary> /// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class to /// watch a specified config file used to configure a repository. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The configuration file to watch.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile) { m_repository = repository; m_configFile = configFile; // Create a new FileSystemWatcher and set its properties. m_watcher = new FileSystemWatcher(); m_watcher.Path = m_configFile.DirectoryName; m_watcher.Filter = m_configFile.Name; // Set the notification filters m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed); // Begin watching. m_watcher.EnableRaisingEvents = true; // Create the timer that will be used to deliver events. Set as disabled m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Event handler used by <see cref="ConfigureAndWatchHandler"/>. /// </summary> /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param> /// <param name="e">The argument indicates the file that caused the event to be fired.</param> /// <remarks> /// <para> /// This handler reloads the configuration from the file when the event is fired. /// </para> /// </remarks> private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e) { LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]"); // Deliver the event in TimeoutMillis time // timer will fire only once m_timer.Change(TimeoutMillis, Timeout.Infinite); } /// <summary> /// Event handler used by <see cref="ConfigureAndWatchHandler"/>. /// </summary> /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param> /// <param name="e">The argument indicates the file that caused the event to be fired.</param> /// <remarks> /// <para> /// This handler reloads the configuration from the file when the event is fired. /// </para> /// </remarks> private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e) { LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]"); // Deliver the event in TimeoutMillis time // timer will fire only once m_timer.Change(TimeoutMillis, Timeout.Infinite); } /// <summary> /// Called by the timer when the configuration has been updated. /// </summary> /// <param name="state">null</param> private void OnWatchedFileChange(object state) { XmlConfigurator.InternalConfigure(m_repository, m_configFile); } /// <summary> /// Release the handles held by the watcher and timer. /// </summary> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif public void Dispose() { m_watcher.EnableRaisingEvents = false; m_watcher.Dispose(); m_timer.Dispose(); } } #endif #endregion ConfigureAndWatchHandler #region Private Static Methods /// <summary> /// Configures the specified repository using a <c>log4net</c> element. /// </summary> /// <param name="repository">The hierarchy to configure.</param> /// <param name="element">The element to parse.</param> /// <remarks> /// <para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </para> /// <para> /// This method is ultimately called by one of the Configure methods /// to load the configuration from an <see cref="XmlElement"/>. /// </para> /// </remarks> static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element) { if (element == null) { LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter"); } else if (repository == null) { LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter"); } else { LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]"); IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator; if (configurableRepository == null) { LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator"); } else { // Copy the xml data into the root of a new document // this isolates the xml config data from the rest of // the document XmlDocument newDoc = new XmlDocument(); XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true)); // Pass the configurator the config element configurableRepository.Configure(newElement); } } } #endregion Private Static Methods #region Private Static Fields /// <summary> /// Maps repository names to ConfigAndWatchHandler instances to allow a particular /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is /// reconfigured. /// </summary> private readonly static Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable(); /// <summary> /// The fully qualified type of the XmlConfigurator class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(XmlConfigurator); #endregion Private Static Fields } }
// // <%=$cur_coll.name%>.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Generated by /CodeGen/cecil-gen.rb do not edit // <%=Time.now%> // // (C) 2005 Jb Evain // // 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. // <% def member_visibility() return $cur_coll.type == "Instruction" ? "internal" : "public" end def use_event?() case $cur_coll.name when "NestedTypeCollection", "MethodDefinitionCollection", "ConstructorCollection", "FieldDefinitionCollection", "EventDefinitionCollection", "PropertyDefinitionCollection" return true end return false end %> namespace <%=$cur_coll.target%> { using System; using System.Collections; using Mono.Cecil.Cil; public sealed class <%=$cur_coll.name%> : CollectionBase<% if (!$cur_coll.visitable.nil?) then %>, <%=$cur_coll.visitable%><% end %> { <%=$cur_coll.container_impl%> m_container;<% if $cur_coll.type == "Instruction" %> public readonly Instruction Outside = new Instruction (int.MaxValue, OpCodes.Nop);<% end %> public <%=$cur_coll.type%> this [int index] { get { return List [index] as <%=$cur_coll.type%>; } set { List [index] = value; } } public <%=$cur_coll.container%> Container { get { return m_container; } } public <%=$cur_coll.name%> (<%=$cur_coll.container_impl%> container) { m_container = container; } <%= member_visibility() %> void Add (<%=$cur_coll.type%> value) {<% if use_event?() %> Attach (value); <% end %> List.Add (value); } <% if use_event?() %> public new void Clear () { foreach (<%=$cur_coll.type%> item in this) Detach (item); base.Clear (); } <% end %> public bool Contains (<%=$cur_coll.type%> value) { return List.Contains (value); } public int IndexOf (<%=$cur_coll.type%> value) { return List.IndexOf (value); } <%= member_visibility() %> void Insert (int index, <%=$cur_coll.type%> value) {<% if use_event?() %> Attach (value); <% end %> List.Insert (index, value); } <%= member_visibility() %> void Remove (<%=$cur_coll.type%> value) { List.Remove (value); <% if use_event?() %> Detach (value); <% end %> } <% if use_event?() %> <%= member_visibility() %> new void RemoveAt (int index) { <%=$cur_coll.type%> item = this [index]; Remove (item); } <% end %> protected override void OnValidate (object o) { if (! (o is <%=$cur_coll.type%>)) throw new ArgumentException ("Must be of type " + typeof (<%=$cur_coll.type%>).FullName); } <% case $cur_coll.item_name when "MethodDefinition" %> public MethodDefinition [] GetMethod (string name) { ArrayList ret = new ArrayList (); foreach (MethodDefinition meth in this) if (meth.Name == name) ret.Add (meth); return ret.ToArray (typeof (MethodDefinition)) as MethodDefinition []; } internal MethodDefinition GetMethodInternal (string name, IList parameters) { foreach (MethodDefinition meth in this) { if (meth.Name != name || meth.Parameters.Count != parameters.Count) continue; bool match = true; for (int i = 0; i < parameters.Count; i++) { string pname; object param = parameters [i]; if (param is Type) pname = ReflectionHelper.GetTypeSignature (param as Type); else if (param is TypeReference) pname = (param as TypeReference).FullName; else if (param is ParameterDefinition) pname = (param as ParameterDefinition).ParameterType.FullName; else throw new NotSupportedException (); if (meth.Parameters [i].ParameterType.FullName != pname) { match = false; break; } } if (match) return meth; } return null; } public MethodDefinition GetMethod (string name, Type [] parameters) { return GetMethodInternal (name, parameters); } public MethodDefinition GetMethod (string name, TypeReference [] parameters) { return GetMethodInternal (name, parameters); } public MethodDefinition GetMethod (string name, ParameterDefinitionCollection parameters) { return GetMethodInternal (name, parameters); } <% when "FieldDefinition" %> public FieldDefinition GetField (string name) { foreach (FieldDefinition field in this) if (field.Name == name) return field; return null; } <% when "Constructor" %> internal MethodDefinition GetConstructorInternal (bool isStatic, IList parameters) { foreach (MethodDefinition ctor in this) { if (ctor.IsStatic != isStatic || ctor.Parameters.Count != parameters.Count) continue; bool match = true; for (int i = 0; i < parameters.Count; i++) { string pname; object param = parameters [i]; if (param is Type) pname = ReflectionHelper.GetTypeSignature (param as Type); else if (param is TypeReference) pname = (param as TypeReference).FullName; else if (param is ParameterDefinition) pname = (param as ParameterDefinition).ParameterType.FullName; else throw new NotSupportedException (); if (ctor.Parameters [i].ParameterType.FullName != pname) { match = false; break; } } if (match) return ctor; } return null; } public MethodDefinition GetConstructor (bool isStatic, Type [] parameters) { return GetConstructorInternal (isStatic, parameters); } public MethodDefinition GetConstructor (bool isStatic, TypeReference [] parameters) { return GetConstructorInternal (isStatic, parameters); } public MethodDefinition GetConstructor (bool isStatic, ParameterDefinitionCollection parameters) { return GetConstructorInternal (isStatic, parameters); } <% when "EventDefinition" %> public EventDefinition GetEvent (string name) { foreach (EventDefinition evt in this) if (evt.Name == name) return evt; return null; } <% when "PropertyDefinition" %> public PropertyDefinition [] GetProperties (string name) { ArrayList ret = new ArrayList (); foreach (PropertyDefinition prop in this) if (prop.Name == name) ret.Add (prop); return ret.ToArray (typeof (PropertyDefinition)) as PropertyDefinition []; } <% end if use_event?() %> void Attach (MemberReference member) { if (member.DeclaringType != null) throw new ReflectionException ("Member already attached, clone it instead"); member.DeclaringType = m_container; } void Detach (MemberReference member) { member.DeclaringType = null; } <% end if !$cur_coll.visitor.nil? then %> public void Accept (<%=$cur_coll.visitor%> visitor) { visitor.<%=$cur_coll.visitThis%> (this); } <% end %> } }
using System; using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; namespace Rainbow.Framework.Content.Data { /// <summary> /// DiscussionEnhanced is an enhanced version of the standard threaded discussion. /// The goal here is to build up to the power of a simple threaded disucssion by /// adding grouping and some other features. /// /// jminond - 3/2005 /// </summary> public class DiscussionEnhancedDB { #region Groups /// <summary> /// Gets the groups in site. /// </summary> /// <param name="PortalID">The portal ID.</param> /// <returns></returns> public SqlDataReader GetGroupsInSite(int PortalID) { throw new NotImplementedException("GetGroupsInSite"); } /// <summary> /// Gets the groups in module. /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetGroupsInModule(int moduleID) { throw new NotImplementedException("GetGroupsInModule"); } /// <summary> /// Return top level messages within a group /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetTopLevelMessages(int moduleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionGetTopLevelMessages", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// Gets the group threads. /// </summary> /// <param name="GroupID">The group ID.</param> /// <returns></returns> public SqlDataReader GetGroupThreads(int GroupID) { throw new NotImplementedException("GetGroupThreads"); } /// <summary> /// Adds the new group. /// </summary> /// <returns></returns> public int AddNewGroup() { throw new NotImplementedException("AddNewGroup"); } #endregion #region Threads /// <summary> /// GetThreadMessages Method /// Returns details for all of the messages the thread, as identified by the Parent id string. /// displayOrder csan be the full display order of any post, it will be truncated /// by the stored procedure to find the root of the thread, and then all children /// are returned /// Other relevant sources: /// + <a href="GetThreadMessages.htm" style="color:green">GetThreadMessages Stored Procedure</a> /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="showRoot">The show root.</param> /// <returns></returns> public SqlDataReader GetThreadMessages(int itemID, char showRoot) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionGetThreadMessages", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterParent = new SqlParameter("@ItemID", SqlDbType.NVarChar, 750); parameterParent.Value = itemID; myCommand.Parameters.Add(parameterParent); // Add Parameters to SPROC SqlParameter parameterShowRoot = new SqlParameter("@IncludeRoot", SqlDbType.Char); parameterShowRoot.Value = showRoot; myCommand.Parameters.Add(parameterShowRoot); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// Deletes the single message. /// </summary> /// <param name="itemID">The item ID.</param> public void DeleteSingleMessage(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionDeleteMessage", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return; } /// <summary> /// Increments the view count. /// </summary> /// <param name="itemID">The item ID.</param> public void IncrementViewCount(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionIncrementViewCount", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return; } /// <summary> /// Deletes the children. /// </summary> /// <param name="itemID">The item ID.</param> /// <returns></returns> public int DeleteChildren(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionDeleteChildren", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterNumDeletedMessages = new SqlParameter("@NumDeletedMessages", SqlDbType.Int, 4); parameterNumDeletedMessages.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterNumDeletedMessages); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return (int) parameterNumDeletedMessages.Value; } /// <summary> /// GetSingleMessage Method /// The GetSingleMessage method returns the details for the message /// specified by the itemID parameter. /// Other relevant sources: /// + <a href="GetSingleMessage.htm" style="color:green">GetSingleMessage Stored Procedure</a> /// </summary> /// <param name="itemID">The item ID.</param> /// <returns></returns> public SqlDataReader GetSingleMessage(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionGetMessage", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// AddMessage Method /// The AddMessage method adds a new message within the /// Discussions database table, and returns ItemID value as a result. /// Other relevant sources: /// + <a href="AddMessage.htm" style="color:green">AddMessage Stored Procedure</a> /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="parentID">The parent ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="body">The body.</param> /// <param name="mode">The mode.</param> /// <returns></returns> public int AddMessage(int moduleID, int parentID, string userName, string title, string body, string mode) { /* ParentID = actual ItemID if this is an edit operation */ if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DiscussionAddMessage", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterMode = new SqlParameter("@Mode", SqlDbType.Text, 20); parameterMode.Value = mode; myCommand.Parameters.Add(parameterMode); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterBody = new SqlParameter("@Body", SqlDbType.NVarChar, 3000); parameterBody.Value = body; myCommand.Parameters.Add(parameterBody); SqlParameter parameterParentID = new SqlParameter("@ParentID", SqlDbType.Int, 4); parameterParentID.Value = parentID; myCommand.Parameters.Add(parameterParentID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterItemID.Value; } #endregion } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using System.Linq; namespace Bam.Core { /// <summary> /// Strings are tokenized by macros and functions. Macros are themselves TokenizedStrings /// and so there is a recursive expansion to evaluate the resulting string (referred to as parsing). /// </summary> /// <remarks> /// Tokens are identified by $( and ). /// A numeric index within a token, e.g. $(0), represents the index into the list of macros passed into the TokenizedString creation function. Parsing is performed recursively, although macros are not shared between repeated parsing calls. /// <para /> /// Functions can run before or after token expansion. /// <para /> /// Pre-functions are run before token expansion, and are identified by \#name(...): /// <list type="bullet"> /// <item><description><code>#valid(expr[,default])</code></description> If the expression is a valid /// TokenizedString, expand it and use it, otherwise the entire function call is replaced with the 'default' expression, unless /// this is omitted, and an empty string is used.</item> /// </list> /// Post-functions are run after token expansion, and are identified by @(...): /// <list type="bullet"> /// <item><description><code>@basename(path)</code></description> Return the filename excluding extension in the path.</item> /// <item><description><code>@filename(path)</code></description> Return the filename including extension in the path.</item> /// <item><description><code>@extension(path)</code></description> Return the extension of the file path. Leading periods are not included.</item> /// <item><description><code>@dir_(path)</code></description> Return the parent directory of path. (Remove the underscore from the name)</item> /// <item><description><code>@normalize(path)</code></description> Return the full path of path, without any special directories.</item> /// <item><description><code>@changeextension(path,ext)</code></description> Change the extension of the file in path, to ext.</item> /// <item><description><code>@removetrailingseparator(path)</code></description> Remove any directory separator characters from the end of path.</item> /// <item><description><code>@relativeto(path,baseDir)</code></description> Return the relative path from baseDir. If there is no common root between them, path is returned.</item> /// <item><description><code>@isrelative(path,fallback)</code></description> If path is relative, use it, otherwise use the fallback.</item> /// <item><description><code>@trimstart(path,totrim)</code></description> Trim string from the start of path.</item> /// <item><description><code>@escapedquotes(path)</code></description> Ensure that the path is double quoted, suitable for use with preprocessor definitions.</item> /// <item><description><code>@ifnotempty(path,whennotempty,whenempty)</code></description> If path is not empty, replace the expression with that in whennotempty, otherwise use whenempty.</item> /// <item><description><code>@tounix(path)</code></description> Convert any Windows paths (using back slashes) to Unix paths (using forward slashes).</item> /// <item><description><code>@exists(path,fallback)</code></description> If the path exists, use it, otherwise use the fallback.</item> /// </list> /// Custom unary post-functions can be registered using <code>registerPostUnaryFunction</code>. /// </remarks> public sealed class TokenizedString { [System.Flags] private enum EFlags { None = 0, ForcedInline = 0x1, NoCache = 0x2 } /// <summary> /// The marker for entry to a token. /// </summary> public static readonly string TokenEntryMarker = @"$"; /// <summary> /// Prefix of each token. /// </summary> public static readonly string TokenPrefix = @"$("; /// <summary> /// Suffix of each token. /// </summary> public static readonly string TokenSuffix = @")"; private static readonly string TokenRegExPattern = @"(\$\([^)]+\))"; private static readonly string ExtractTokenRegExPattern = @"\$\(([^)]+)\)"; private static readonly string PositionalTokenRegExPattern = @"\$\(([0-9]+)\)"; // pre-functions look like: #functionname(expression) // note: this is using balancing groups in order to handle nested function calls, or any other instances of parentheses in paths (e.g. Windows 'Program Files (x86)') private static readonly string PreFunctionRegExPattern = @"(#(?<func>[a-z]+)\((?<expression>[^\(\)]+|\((?<Depth>)|\)(?<-Depth>))*(?(Depth)(?!))\))"; // post-functions look like: @functionname(expression) // note: this is using balancing groups in order to handle nested function calls, or any other instances of parentheses in paths (e.g. Windows 'Program Files (x86)') private static readonly string PostFunctionRegExPattern = @"(@(?<func>[a-z]+)\((?<expression>[^\(\)]+|\((?<Depth>)|\)(?<-Depth>))*(?(Depth)(?!))\))"; private static readonly string[] BuiltInPostFunctionNames = { "basename", "filename", "extension", "dir", "normalize", "changeextension", "removetrailingseparator", "relativeto", "isrelative", "trimstart", "escapedquotes", "ifnotempty", "tounix", "exists" }; // static fields, initialised in reset() private static System.Collections.Generic.Dictionary<System.Int64, TokenizedString> VerbatimCacheMap; private static System.Collections.Generic.Dictionary<System.Int64, TokenizedString> NoModuleCacheMap; private static System.Collections.Generic.List<TokenizedString> AllStrings; private static System.Collections.Generic.List<TokenizedString> StringsForParsing = new System.Collections.Generic.List<TokenizedString>(); private static bool AllStringsParsed; private static System.Collections.Generic.Dictionary<string, System.Func<string, string>> CustomPostUnaryFunctions; private static System.TimeSpan RegExTimeout; private static bool RecordStackTraces; // instance fields private System.Collections.Generic.List<string> Tokens = null; private Module ModuleWithMacros = null; private string OriginalString = null; private string ParsedString = null; private readonly object ParsedStringGuard = new object(); // since you can't lock ParsedString as it may be null private bool Verbatim; private TokenizedStringArray PositionalTokens = null; private string CreationStackTrace = null; private int RefCount = 1; private readonly EFlags Flags = EFlags.None; private long hash = 0; private string parsedStackTrace = null; /// <summary> /// Register a custom unary post function to use in TokenizedString parsing. /// The name must not collide with any built-in functions, or any existing custom unary post functions. /// </summary> /// <param name="name">Name of the function that must be unique.</param> /// <param name="function">Function to apply to any usage of \p name in TokenizedStrings.</param> public static void RegisterPostUnaryFunction( string name, System.Func<string, string> function) { if (BuiltInPostFunctionNames.Contains(name)) { throw new Exception($"Unable to register post unary function due to name collision with builtin functions, '{name}'"); } if (CustomPostUnaryFunctions.ContainsKey(name)) { throw new Exception($"Unable to register post unary function because post function '{name}' already exists."); } CustomPostUnaryFunctions.Add(name, function); } static private System.Collections.Generic.IEnumerable<string> SplitIntoTokens( string original, string regExPattern) { var regExSplit = System.Text.RegularExpressions.Regex.Split(original, regExPattern); var filtered = regExSplit.Where(item => !System.String.IsNullOrEmpty(item)); return filtered; } static private System.Collections.Generic.IEnumerable<string> GetMatches( string original, string regExPattern) { var matches = System.Text.RegularExpressions.Regex.Matches(original, regExPattern); foreach (System.Text.RegularExpressions.Match match in matches) { // was at least one substring captured by the regex? if (!match.Success) { continue; } // there is >1 groups, as the first is the original expression, so skip it foreach (var group in match.Groups.Cast<System.Text.RegularExpressions.Group>().Skip(1)) { yield return group.Value; } } } private static string GetStacktrace() { if (RecordStackTraces) { return System.Environment.StackTrace; } return string.Empty; } /// <summary> /// Reset all static state of the TokenizedString class. /// This function is only really useful in unit tests. /// </summary> public static void Reset() { VerbatimCacheMap = new System.Collections.Generic.Dictionary<System.Int64, TokenizedString>(); NoModuleCacheMap = new System.Collections.Generic.Dictionary<System.Int64, TokenizedString>(); AllStrings = new System.Collections.Generic.List<TokenizedString>(); StringsForParsing = new System.Collections.Generic.List<TokenizedString>(); AllStringsParsed = false; CustomPostUnaryFunctions = new System.Collections.Generic.Dictionary<string, System.Func<string, string>>(); RecordStackTraces = false; RegExTimeout = System.TimeSpan.FromSeconds(5); } static TokenizedString() { Reset(); RecordStackTraces = CommandLineProcessor.Evaluate(new Options.RecordStackTrace()); if (RecordStackTraces) { Log.Info("WARNING: TokenizedString stack trace recording enabled. This will slow down your build."); } } private TokenizedString( string original, Module moduleWithMacros, bool verbatim, TokenizedStringArray positionalTokens, EFlags flags) { this.ModuleWithMacros = moduleWithMacros; this.Verbatim = verbatim; this.Flags |= flags; this.SetInternal(original, (null != positionalTokens) ? positionalTokens.ToArray() : null); if (verbatim) { this.ParsedString = original; this.parsedStackTrace = GetStacktrace(); } } private static System.Int64 CalculateHash( string tokenizedString, Module macroSource, bool verbatim, TokenizedStringArray positionalTokens) { // https://cs.stackexchange.com/questions/45287/why-does-this-particular-hashcode-function-help-decrease-collisions System.Int64 hash = 17; hash = hash * 31 + tokenizedString.GetHashCode(); if (!verbatim) { if (null != macroSource) { hash = hash * 31 + macroSource.GetHashCode(); } if (null != positionalTokens) { foreach (var posToken in positionalTokens) { hash = hash * 31 + posToken.GetHashCode(); } } } return hash; } private static TokenizedString CreateInternal( string tokenizedString, Module macroSource, bool verbatim, TokenizedStringArray positionalTokens, EFlags flags) { if (null == tokenizedString) { return null; } var hash = CalculateHash(tokenizedString, macroSource, verbatim, positionalTokens); // strings can be created during the multithreaded phase, so synchronize on the cache used if (verbatim) { // covers all verbatim strings lock (VerbatimCacheMap) { var useCache = (0 == (flags & EFlags.NoCache)); if (useCache) { if (VerbatimCacheMap.TryGetValue(hash, out TokenizedString foundTS)) { ++foundTS.RefCount; return foundTS; } } var newTS = new TokenizedString(tokenizedString, macroSource, verbatim, positionalTokens, flags); if (useCache) { VerbatimCacheMap.Add(hash, newTS); } newTS.hash = hash; lock (AllStrings) { AllStrings.Add(newTS); } return newTS; } } else { // covers all strings associated with a module (for macros), or no module but with positional arguments var stringCache = (null != macroSource) ? macroSource.TokenizedStringCacheMap : NoModuleCacheMap; lock (stringCache) { var useCache = (0 == (flags & EFlags.NoCache)); if (useCache) { if (stringCache.TryGetValue(hash, out TokenizedString foundTS)) { ++foundTS.RefCount; return foundTS; } } var newTS = new TokenizedString(tokenizedString, macroSource, verbatim, positionalTokens, flags); if (useCache) { stringCache.Add(hash, newTS); } newTS.hash = hash; lock (AllStrings) { AllStrings.Add(newTS); } if (!newTS.IsForcedInline) { lock (StringsForParsing) { StringsForParsing.Add(newTS); } } return newTS; } } } /// <summary> /// Utility method to create a TokenizedString associated with a module, or return a cached version. /// </summary> /// <param name="tokenizedString">Tokenized string.</param> /// <param name="macroSource">Macro source.</param> /// <param name="positionalTokens">Positional tokens.</param> public static TokenizedString Create( string tokenizedString, Module macroSource, TokenizedStringArray positionalTokens = null) => CreateInternal(tokenizedString, macroSource, false, positionalTokens, EFlags.None); /// <summary> /// Utility method to create a TokenizedString with no macro replacement, or return a cached version. /// </summary> /// <returns>The verbatim.</returns> /// <param name="verboseString">Verbose string.</param> public static TokenizedString CreateVerbatim( string verboseString) => CreateInternal(verboseString, null, true, null, EFlags.None); /// <summary> /// Utility method to create a TokenizedString that can be inlined into other TokenizedStrings /// , or return a cached version. /// </summary> /// <returns>The inline.</returns> /// <param name="inlineString">Inline string.</param> public static TokenizedString CreateForcedInline( string inlineString) => CreateInternal(inlineString, null, false, null, EFlags.ForcedInline); /// <summary> /// Utility method to create a TokenizedString which will not be cached with any other existing /// TokenizedStrings that share the same original string. /// Such TokenizedStrings are intended to be aliased at a future time. /// </summary> /// <param name="uncachedString">The string that will be uncached.</param> /// <param name="macroSource">The Module containing macros that will be eventually referenced.</param> /// <param name="positionalTokens">Positional tokens.</param> /// <returns>A unique TokenizedString.</returns> public static TokenizedString CreateUncached( string uncachedString, Module macroSource, TokenizedStringArray positionalTokens = null) => CreateInternal(uncachedString, macroSource, false, positionalTokens, EFlags.NoCache); /// <summary> /// Determine if the TokenizedString has been parsed already. /// Sometimes useful if a TokenizedString is created after the ParseAll step, but is repeated /// as a dependency. /// </summary> public bool IsParsed { get { if (this.Verbatim) { return true; } if (this.IsForcedInline) { return false; } var hasTokens = (null != this.Tokens); lock (this.ParsedStringGuard) { var hasParsedString = (null != this.ParsedString); return !hasTokens && hasParsedString; } } } private static string NormalizeDirectorySeparators( string path) => OSUtilities.IsWindowsHosting ? path.Replace('/', '\\') : path.Replace('\\', '/'); /// <summary> /// Return the parsed string. /// If the string has not been parsed, or unsuccessfully parsed, an exception is thrown. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="Bam.Core.TokenizedString"/>.</returns> public override string ToString() { if (null == this.ParsedString) { var message = new System.Text.StringBuilder(); var parsingPhase = AllStringsParsed ? " after the string parsing phase" : string.Empty; message.AppendLine($"TokenizedString '{this.OriginalString}' has not been parsed{parsingPhase}"); message.AppendLine(); message.AppendLine("Created at:"); message.AppendLine(this.CreationStackTrace); throw new Exception(message.ToString()); } if (null != this.Tokens) { var message = new System.Text.StringBuilder(); var parsingPhase = AllStringsParsed ? " after the string parsing phase" : string.Empty; message.AppendLine($"TokenizedString '{this.OriginalString}' has been parsed to"); message.AppendLine($"'{this.ParsedString}'"); message.AppendLine($"but the following tokens remain unresolved{parsingPhase}:"); foreach (var token in this.Tokens) { if (!token.StartsWith(TokenPrefix, System.StringComparison.Ordinal)) { continue; } message.AppendLine($"\t{token}"); } message.AppendLine(); message.AppendLine("Created at:"); message.AppendLine(this.CreationStackTrace); throw new Exception(message.ToString()); } return this.ParsedString; } /// <summary> /// Determine if the string is empty. /// </summary> /// <value><c>true</c> if empty; otherwise, <c>false</c>.</value> public bool Empty => (null == this.Tokens) || !this.Tokens.Any(); private bool IsForcedInline => (EFlags.ForcedInline == (this.Flags & EFlags.ForcedInline)); /// <summary> /// Parse every TokenizedString. /// </summary> public static void ParseAll() { Log.Detail("Parsing strings..."); var scale = 100.0f / StringsForParsing.Count; var count = 0; foreach (var t in StringsForParsing) { t.ParseInternalWithAlreadyParsedCheck(null); Log.DetailProgress("{0,3}%", (int)(++count * scale)); } AllStringsParsed = true; } /// <summary> /// Parsed a TokenizedString. /// Pre-functions are evaluated first. /// The order of source of tokens are checked in the follow order: /// - Positional tokens. /// - Any custom macros (will be none in this context) /// - Global macros (from the Graph) /// - Macros in the associated Module /// - Macros in the Tool associated with the Module /// - Environment variables /// After token expansion, post-functions are then evaluated. /// No string is returned, use ToString(). /// Failure to parse are stored in the TokenizedString and will be displayed as an exception /// message when used. /// </summary> public void Parse() { if (this.ParsedString != null) { var message = new System.Text.StringBuilder(); var parsePhase = AllStringsParsed ? " after the string parsing phase" : string.Empty; message.AppendLine($"TokenizedString '{this.OriginalString}' is already parsed{parsePhase}."); message.AppendLine(); message.AppendLine("Created at:"); message.AppendLine(this.CreationStackTrace); message.AppendLine(); message.AppendLine("Parsed at:"); message.AppendLine(this.parsedStackTrace); throw new Exception(message.ToString()); } lock (this.ParsedStringGuard) { this.ParseInternalWithAlreadyParsedCheck(null); } lock (StringsForParsing) { StringsForParsing.Remove(this); } } /// <summary> /// Parsed a TokenizedString with a custom source of macro overrides. /// This performs a similar operation to Parse(), except that the parsed string is not saved, but is returned /// from the function. /// This allows TokenizedStrings to be re-parsed with different semantics to their tokens, but will not affect /// the existing parse result. /// The array of MacroLists is evaluated from front to back, so if there are duplicate macros in several MacroLists /// the first encountered will be the chosen value. /// No errors or exceptions are reported or saved from using this function, so use it sparingly and with care. /// </summary> /// <param name="customMacroArray">Array of custom macros.</param> public string UncachedParse( Array<MacroList> customMacroArray) => this.ParseInternal(customMacroArray); private string ParseInternalWithAlreadyParsedCheck( Array<MacroList> customMacroArray) => this.ParsedString ?? this.ParseInternal(customMacroArray); private string GetParsedString( Array<MacroList> customMacroArray) { if (null == this.ParsedString) { this.ParseInternal(customMacroArray); //throw new Exception($"String '{this.OriginalString}' has yet to be parsed"); } return this.ParsedString; } private void ExtendParsedStringWrapper( TokenizedString stringToExtendWith, System.Text.StringBuilder parsedString, Array<MacroList> customMacroArray, System.Collections.Generic.List<string> tokens, int index) { if (stringToExtendWith.IsForcedInline) { var extTokens = SplitIntoTokens(this.EvaluatePreFunctions(stringToExtendWith.OriginalString, customMacroArray), TokenRegExPattern).ToList<string>(); if (null != extTokens) { tokens.InsertRange(index, extTokens); } else { parsedString.Append(stringToExtendWith.OriginalString); } } else { stringToExtendWith.ExtendParsedString(parsedString, customMacroArray, tokens, index); } } private void ExtendParsedString( System.Text.StringBuilder parsedString, Array<MacroList> customMacroArray, System.Collections.Generic.List<string> tokens, int index) { var parsedResult = this.GetParsedString(customMacroArray); if (null != this.Tokens) { tokens.InsertRange(index, this.Tokens); } else { parsedString.Append(parsedResult); } } private string ParseInternal( Array<MacroList> customMacroArray) { if (this.IsForcedInline) { throw new Exception($"Forced inline TokenizedString cannot be parsed, {this.OriginalString}"); } var graph = Graph.Instance; var parsedString = new System.Text.StringBuilder(); var tokens = SplitIntoTokens(this.EvaluatePreFunctions(this.OriginalString, customMacroArray), TokenRegExPattern).ToList<string>(); for (int index = 0; index < tokens.Count;) { var token = tokens[index]; // if not identified as a token, just add the string, and move along if (!(token.StartsWith(TokenPrefix, System.StringComparison.Ordinal) && token.EndsWith(TokenSuffix, System.StringComparison.Ordinal))) { // unless it sort of looks like a token, but has bad formatting // $token will not throw though if (token.StartsWith(TokenEntryMarker)) { if (token.StartsWith(TokenPrefix, System.StringComparison.Ordinal) || token.EndsWith(TokenSuffix, System.StringComparison.Ordinal)) { throw new BadTokenFormatException(token); } } parsedString.Append(token); tokens.Remove(token); continue; } // step 1: if the token is a positional token, inline it, and add outstanding tokens var positional = GetMatches(token, PositionalTokenRegExPattern).FirstOrDefault(); if (!System.String.IsNullOrEmpty(positional)) { var positionalIndex = System.Convert.ToInt32(positional); if (positionalIndex > this.PositionalTokens.Count) { throw new Exception( $"TokenizedString positional token at index {positionalIndex} requested, but only {this.PositionalTokens.Count} positional values given. Created at {this.CreationStackTrace}." ); } try { var posTokenStr = this.PositionalTokens[positionalIndex]; tokens.Remove(token); this.ExtendParsedStringWrapper(posTokenStr, parsedString, customMacroArray, tokens, index); } catch (System.ArgumentOutOfRangeException ex) { throw new Exception( ex, $"Positional token index {positionalIndex} exceeded number of tokens available {this.PositionalTokens.Count}" ); } continue; } // step 2 : try to resolve with custom macros passed to the Parse function if (null != customMacroArray?.FirstOrDefault(item => item.Dict.ContainsKey(token))) { var containingMacroList = customMacroArray.First(item => item.Dict.ContainsKey(token)); var customTokenStr = containingMacroList.Dict[token]; tokens.Remove(token); this.ExtendParsedStringWrapper(customTokenStr, parsedString, customMacroArray, tokens, index); continue; } // step 3 : try macros in the global Graph, common to all modules if (graph.Macros.Dict.ContainsKey(token)) { var graphTokenStr = graph.Macros.Dict[token]; tokens.Remove(token); this.ExtendParsedStringWrapper(graphTokenStr, parsedString, customMacroArray, tokens, index); continue; } if (this.ModuleWithMacros != null) { var tool = this.ModuleWithMacros.Tool; // step 4 : try macros in the specific module if (this.ModuleWithMacros.Macros.Dict.ContainsKey(token)) { var moduleMacroStr = this.ModuleWithMacros.Macros.Dict[token]; tokens.Remove(token); this.ExtendParsedStringWrapper(moduleMacroStr, parsedString, customMacroArray, tokens, index); continue; } // step 5 : try macros in the Tool attached to the specific module else if (null != tool && tool.Macros.Dict.ContainsKey(token)) { var moduleToolMacroStr = tool.Macros.Dict[token]; tokens.Remove(token); this.ExtendParsedStringWrapper(moduleToolMacroStr, parsedString, customMacroArray, tokens, index); continue; } } // step 6 : try the immediate environment var strippedToken = SplitIntoTokens(token, ExtractTokenRegExPattern).First(); if (System.String.Equals(token, strippedToken, System.StringComparison.Ordinal)) { throw new EmptyStringException(); } var envVar = System.Environment.GetEnvironmentVariable(strippedToken); if (null != envVar) { tokens.Remove(token); parsedString.Append(envVar); continue; } // step 7 : original token must be honoured, as it might be resolved in a later inlining step parsedString.Append(token); ++index; } if (tokens.Any()) { if (null != customMacroArray) { throw new Exception("String cannot be fully parsed with the custom macros provided"); } // need to split into tokens again // so that both unresolved tokens and literal text can be inserted into future strings this.Tokens = SplitIntoTokens(parsedString.ToString(), TokenRegExPattern).ToList<string>(); this.ParsedString = parsedString.ToString(); Log.DebugMessage($"\t'{this.OriginalString}' --> '{this.ParsedString}'"); return this.ParsedString; } else { this.Tokens = null; var functionEvaluated = this.EvaluatePostFunctions(NormalizeDirectorySeparators(parsedString.ToString())); // when using a custom array of MacroLists, do not store the parsed string // instead just return it // this allows a TokenizedString to be re-parsed with different semantics, but does not // permanently change it if (null == customMacroArray) { this.ParsedString = functionEvaluated; this.parsedStackTrace = GetStacktrace(); Log.DebugMessage($" '{this.OriginalString}' --> '{this.ToString()}'"); } else { Log.DebugMessage($" '{this.OriginalString}' --> '{functionEvaluated}' (using custom macros)"); } return functionEvaluated; } } private string EvaluatePostFunctions( string sourceExpression) { System.Text.RegularExpressions.MatchCollection matches = null; try { matches = System.Text.RegularExpressions.Regex.Matches( sourceExpression, PostFunctionRegExPattern, System.Text.RegularExpressions.RegexOptions.None, RegExTimeout); if (!matches.Any()) { return sourceExpression; } } catch (System.Text.RegularExpressions.RegexMatchTimeoutException) { var message = new System.Text.StringBuilder(); message.AppendLine($"TokenizedString post-function regular expression matching timed out after {RegExTimeout.Seconds} seconds. Check details below for errors."); message.AppendLine($"String being parsed: {sourceExpression}"); message.AppendLine($"Regex : {PostFunctionRegExPattern}"); message.AppendLine($"Tokenized string {this.OriginalString} created at"); message.AppendLine(this.CreationStackTrace); throw new Exception(message.ToString()); } var modifiedString = sourceExpression; foreach (System.Text.RegularExpressions.Match match in matches) { var functionName = match.Groups["func"].Value; // this correctly obtains the expression when nested functions are present var expressionText = new System.Text.StringBuilder(); foreach (System.Text.RegularExpressions.Capture capture in match.Groups["expression"].Captures) { expressionText.Append(capture.Value); } var expression = this.EvaluatePostFunctions(expressionText.ToString()); var expandedExpression = this.FunctionExpression(functionName, expression); modifiedString = modifiedString.Replace(match.Value, expandedExpression); } return modifiedString; } private string FunctionExpression( string functionName, string argument) { switch (functionName) { case "basename": return System.IO.Path.GetFileNameWithoutExtension(argument); case "filename": return System.IO.Path.GetFileName(argument); case "extension": return System.IO.Path.GetExtension(argument).TrimStart('.'); case "dir": return System.IO.Path.GetDirectoryName(argument); case "normalize": return System.IO.Path.GetFullPath(argument); case "changeextension": { var split = argument.Split(','); if (split.Length != 2) { throw new Exception( $"Expected 2, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var original = split[0]; var extension = split[1].Trim(); var changed = System.IO.Path.ChangeExtension(original, extension); return changed; } case "removetrailingseparator": return argument.TrimEnd(System.IO.Path.DirectorySeparatorChar); case "relativeto": { var split = argument.Split(','); if (split.Length != 2) { throw new Exception( $"Expected 2, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var path = split[0]; var root = split[1] + System.IO.Path.DirectorySeparatorChar; var relative = System.IO.Path.GetRelativePath(root, path); return relative; } case "isrelative": { var split = argument.Split(','); if (split.Length != 2) { throw new Exception( $"Expected 2, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var path = split[0]; var fallback = split[1]; if (System.IO.Path.IsPathRooted(path)) { return fallback; } else { return path; } } case "trimstart": { var split = argument.Split(','); if (split.Length != 2) { throw new Exception( $"Expected 2, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var original = split[0]; var totrim = split[1]; while (true) { var index = original.IndexOf(totrim); if (index != 0) { break; } original = original.Substring(index + totrim.Length); } return original; } case "escapedquotes": { if (OSUtilities.IsWindowsHosting) { // on Windows, escape any backslashes, as these are normal Windows paths // so don't interpret them as control characters argument = argument.Replace("\\", "\\\\"); } return $"\"{argument}\""; } case "ifnotempty": { var split = argument.Split(','); if (split.Length != 3) { throw new Exception( $"Expected 3, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var predicateString = split[0]; if (!System.String.IsNullOrEmpty(predicateString)) { var positiveString = split[1]; return positiveString; } else { var negativeString = split[2]; return negativeString; } } case "tounix": { argument = argument.Replace("\\", "/"); return argument; } case "exists": { var split = argument.Split(','); if (split.Length != 2) { throw new Exception( $"Expected 2, not {split.Length}, arguments in the function call {functionName}({argument}) in {this.OriginalString}" ); } var path = split[0]; var fallback = split[1]; if (System.IO.File.Exists(path) || System.IO.Directory.Exists(path)) { return path; } return fallback; } default: { // search through custom functions if (CustomPostUnaryFunctions.ContainsKey(functionName)) { return CustomPostUnaryFunctions[functionName](argument); } throw new Exception( $"Unknown post-function '{functionName}' in TokenizedString '{this.OriginalString}'" ); } } } /// <summary> /// Does the string contain a space? /// </summary> /// <value><c>true</c> if contains space; otherwise, <c>false</c>.</value> public bool ContainsSpace { get { if (!this.IsParsed) { throw new Exception($"TokenizedString, '{this.OriginalString}', is not yet expanded"); } if (null != this.ParsedString) { return this.ParsedString.Contains(' '); } else { if (this.Tokens.Count != 1) { throw new Exception("Tokenized string that is expanded, but has more than one token"); } return this.Tokens[0].Contains(' '); } } } /// <summary> /// Are two strings identical? This includes comparing how the string was constructed. /// It does not necessarily mean that the parsed strings are identical. Use ToString().Equals() to achieve that test. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Bam.Core.TokenizedString"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="Bam.Core.TokenizedString"/>; otherwise, <c>false</c>.</returns> public override bool Equals( object obj) { var other = obj as TokenizedString; var equals = this.hash == other.hash; return equals; } /// <summary> /// Required by the Equals override. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() => base.GetHashCode(); /// <summary> /// Quote the string if it contains a space /// </summary> /// <returns>The string and quote if necessary.</returns> public string ToStringQuoteIfNecessary() => IOWrapper.EncloseSpaceContainingPathWithDoubleQuotes(this.ToString()); /// <summary> /// Static utility method to return the number of TokenizedStrings cached. /// </summary> /// <value>The count.</value> public static int Count => AllStrings.Count(); /// <summary> /// Static utility method to return the number of strings with a single refcount. /// </summary> /// <value>The unshared count.</value> public static int UnsharedCount => AllStrings.Where(item => item.RefCount == 1).Count(); /// <summary> /// In debug builds, dump data representing all of the tokenized strings. /// </summary> [System.Diagnostics.Conditional("DEBUG")] public static void DumpCache() { Log.DebugMessage("Tokenized string cache"); foreach (var item in AllStrings.OrderBy(item => item.RefCount).ThenBy(item => !item.Verbatim)) { var isVerbatimOpen = item.Verbatim ? "<verbatim>" : string.Empty; var isVerbatimClose = item.Verbatim ? "</verbatim>" : string.Empty; var moduleReference = item.ModuleWithMacros != null ? $"(ref: {item.ModuleWithMacros.GetType().ToString()})" : string.Empty; Log.DebugMessage( $"#{item.RefCount} {isVerbatimOpen}'{item.OriginalString}'{isVerbatimClose} {moduleReference}" ); } } private bool IsTokenValid( string token, Array<MacroList> customMacroArray) { // step 1 : is the token positional, i.e. was set up at creation time var positional = GetMatches(token, PositionalTokenRegExPattern).FirstOrDefault(); if (!System.String.IsNullOrEmpty(positional)) { var positionalIndex = System.Convert.ToInt32(positional); return (positionalIndex <= this.PositionalTokens.Count); } // step 2 : try to resolve with custom macros passed to the Parse function else if (null != customMacroArray?.FirstOrDefault(item => item.Dict.ContainsKey(token))) { return true; } // step 3 : try macros in the global Graph, common to all modules else if (Graph.Instance.Macros.Dict.ContainsKey(token)) { return true; } else if (this.ModuleWithMacros != null) { var tool = this.ModuleWithMacros.Tool; // step 4 : try macros in the specific module if (this.ModuleWithMacros.Macros.Dict.ContainsKey(token)) { return true; } // step 5 : try macros in the Tool attached to the specific module else if (null != tool && tool.Macros.Dict.ContainsKey(token)) { return true; } } // step 6 : try the immediate environment var strippedToken = SplitIntoTokens(token, ExtractTokenRegExPattern).First(); var envVar = System.Environment.GetEnvironmentVariable(strippedToken); if (null != envVar) { return true; } // step 7 : fail else { return false; } } private string EvaluatePreFunctions( string originalExpression, Array<MacroList> customMacroArray) { System.Text.RegularExpressions.MatchCollection matches = null; try { matches = System.Text.RegularExpressions.Regex.Matches( originalExpression, PreFunctionRegExPattern, System.Text.RegularExpressions.RegexOptions.None, RegExTimeout); if (!matches.Any()) { return originalExpression; } } catch (System.Text.RegularExpressions.RegexMatchTimeoutException) { var message = new System.Text.StringBuilder(); message.AppendLine($"TokenizedString pre-function regular expression matching timed out after {RegExTimeout.Seconds} seconds. Check details below for errors."); message.AppendLine($"String being parsed: {originalExpression}"); message.AppendLine($"Regex : {PreFunctionRegExPattern}"); message.AppendLine($"Tokenized string {this.OriginalString} created at"); message.AppendLine(this.CreationStackTrace); throw new Exception(message.ToString()); } var modifiedString = originalExpression; foreach (System.Text.RegularExpressions.Match match in matches) { var functionName = match.Groups["func"].Value; // this correctly obtains the expression when nested functions are present var expressionText = new System.Text.StringBuilder(); foreach (System.Text.RegularExpressions.Capture capture in match.Groups["expression"].Captures) { expressionText.Append(capture.Value); } var expression = this.EvaluatePreFunctions(expressionText.ToString(), customMacroArray); switch (functionName) { case "valid": { var split = expression.Split(','); var replacement = (1 == split.Length) ? string.Empty : split[1]; var tokens = SplitIntoTokens(split[0], TokenRegExPattern); var allTokensValid = true; foreach (var token in tokens) { if (!(token.StartsWith(TokenPrefix, System.StringComparison.Ordinal) && token.EndsWith(TokenSuffix, System.StringComparison.Ordinal))) { continue; } // Note: with nested valid pre-functions, macros can be validated as many times as they are nested if (this.IsTokenValid(token, customMacroArray)) { continue; } allTokensValid = false; break; } if (allTokensValid) { modifiedString = modifiedString.Replace(match.Value, split[0]); } else { modifiedString = modifiedString.Replace(match.Value, replacement); } } break; default: throw new Exception($"Unknown pre-function '{functionName}' in TokenizedString '{this.OriginalString}'"); } } return modifiedString; } /// <summary> /// Remove all strings referencing a module type, including those that are not yet parsed. /// </summary> /// <param name="moduleType"></param> static public void RemoveEncapsulatedStrings( System.Type moduleType) { lock (AllStrings) { var toRemove = AllStrings.Where( item => item.ModuleWithMacros != null && item.ModuleWithMacros.GetType() == moduleType); foreach (var i in toRemove.ToList()) { i.RefCount--; if (0 == i.RefCount) { Log.DebugMessage($"Removing string {i.OriginalString} from {moduleType.ToString()}"); AllStrings.Remove(i); // Don't believe a separate lock is needed for StringsForParsing if (StringsForParsing.Contains(i)) { StringsForParsing.Remove(i); } } } } } /// <summary> /// Clone a TokenizedString, but reassign the Module containing macros. /// Verbatim strings are returned directly. /// </summary> /// <returns>Clone of the string, using the specified module as macro source. Or the verbatim string directly.</returns> public TokenizedString Clone( Module moduleWithMacros) { if (this.Verbatim) { return this; } else { return Create(this.OriginalString, moduleWithMacros, this.PositionalTokens); } } /// <summary> /// Determine if a macro is referred to in the string /// or any of it's positional string arguments. /// </summary> /// <param name="macro">Macro name to look up, including $( and $) prefix and suffix</param> /// <returns></returns> public bool RefersToMacro( string macro) { if (!(macro.StartsWith(TokenizedString.TokenPrefix, System.StringComparison.Ordinal) && macro.EndsWith(TokenizedString.TokenSuffix, System.StringComparison.Ordinal))) { throw new Exception($"Invalid macro key: {macro}"); } var inString = this.OriginalString.Contains(macro); if (inString) { return true; } foreach (var positional in this.PositionalTokens) { if (positional.RefersToMacro(macro)) { return true; } } return false; } private void SetInternal( string newString, TokenizedString[] positionalTokens) { if (null != this.ParsedString) { throw new Exception( $"Cannot change the TokenizedString '{this.OriginalString}' to '{newString}' as it has been parsed already" ); } this.CreationStackTrace = GetStacktrace(); this.PositionalTokens = new TokenizedStringArray(); if (null != positionalTokens) { this.PositionalTokens.AddRange(positionalTokens); } this.OriginalString = newString; } /// <summary> /// Change an existing TokenizedString's definition. This is only possible when the string has yet to be parsed. /// </summary> /// <param name="newString">Unparsed token based string to use.</param> /// <param name="positionalTokens">Any positional arguments referenced in the unparsed string.</param> public void Set( string newString, TokenizedString[] positionalTokens) { this.SetInternal(newString, positionalTokens); var newHash = CalculateHash(this.OriginalString, this.ModuleWithMacros, this.Verbatim, this.PositionalTokens); if (0 == (Flags & EFlags.NoCache)) { // update previous caches if (this.Verbatim) { lock (VerbatimCacheMap) { VerbatimCacheMap.Remove(this.hash); VerbatimCacheMap.Add(newHash, this); } } else { var cache = (this.ModuleWithMacros != null) ? this.ModuleWithMacros.TokenizedStringCacheMap : NoModuleCacheMap; lock (cache) { cache.Remove(this.hash); cache.Add(newHash, this); } } } this.hash = newHash; } /// <summary> /// Extract the unparsed string, containing all original tokens. /// </summary> public string UnparsedString => this.OriginalString; /// <summary> /// Exception thrown when a TokenizedString has an empty token, i.e. "$()" /// </summary> public sealed class EmptyStringException : Exception {} /// <summary> /// Exception thrown when a TokenizedString contains bad token formatting, e.g. "$token)" is missing the opening parenthesis scope /// </summary> public sealed class BadTokenFormatException : Exception { /// <summary> /// Exception constructor. /// </summary> /// <param name="message">Exception message.</param> public BadTokenFormatException( string message) : base(message) {} } } }
namespace Nancy.ViewEngines { using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; /// <summary> /// A super-simple view engine /// </summary> public class SuperSimpleViewEngine { /// <summary> /// Compiled Regex for single substitutions /// </summary> private readonly Regex singleSubstitutionsRegEx = new Regex(@"@Model(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for each blocks /// </summary> private readonly Regex eachSubstitutionRegEx = new Regex(@"@Each(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?(?<Contents>.*?)@EndEach;?", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled Regex for each block current substitutions /// </summary> private readonly Regex eachItemSubstitutionRegEx = new Regex(@"@Current(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for if blocks /// </summary> private readonly Regex conditionalSubstitutionRegEx = new Regex(@"@If(?<Not>Not)?(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?(?<Contents>.*?)@EndIf;?", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// View engine transform processors /// </summary> private readonly List<Func<string, object, string>> processors; /// <summary> /// Initializes a new instance of the <see cref="SuperSimpleViewEngine"/> class. /// </summary> public SuperSimpleViewEngine() { this.processors = new List<Func<string, object, string>> { this.PerformSingleSubstitutions, this.PerformEachSubstitutions, this.PerformConditionalSubstitutions, }; } /// <summary> /// Renders a template /// </summary> /// <param name="template">The template to render.</param> /// <param name="model">The model to user for rendering.</param> /// <returns>A string containing the expanded template.</returns> public string Render(string template, dynamic model) { if (model == null) { return template; } return this.processors.Aggregate(template, (current, processor) => processor(current, model)); } /// <summary> /// <para> /// Gets a property value from the given model. /// </para> /// <para> /// Anonymous types, standard types and ExpandoObject are supported. /// Arbitrary dynamics (implementing IDynamicMetaObjectProvicer) are not, unless /// they also implmennt IDictionary string, object for accessing properties. /// </para> /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name to evaluate.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was sucessful, Item2 being the value.</returns> /// <exception cref="ArgumentException">Model type is not supported.</exception> private static Tuple<bool, object> GetPropertyValue(object model, string propertyName) { if (model == null || String.IsNullOrEmpty(propertyName)) { return new Tuple<bool, object>(false, null); } if (!typeof(IDynamicMetaObjectProvider).IsAssignableFrom(model.GetType())) { return StandardTypePropertyEvaluator(model, propertyName); } if (typeof(IDictionary<string, object>).IsAssignableFrom(model.GetType())) { return DynamicDictionaryPropertyEvaluator(model, propertyName); } throw new ArgumentException("model must be a standard type or implement IDictionary<string, object>", "model"); } /// <summary> /// A property extractor for standard types. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was sucessful, Item2 being the value.</returns> private static Tuple<bool, object> StandardTypePropertyEvaluator(object model, string propertyName) { var properties = model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var property = properties.Where(p => String.Equals(p.Name, propertyName, StringComparison.InvariantCulture)). FirstOrDefault(); return property == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, property.GetValue(model, null)); } /// <summary> /// A property extractor designed for ExpandoObject, but also for any /// type that implements IDictionary string object for accessing its /// properties. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was sucessful, Item2 being the value.</returns> private static Tuple<bool, object> DynamicDictionaryPropertyEvaluator(object model, string propertyName) { var dictionaryModel = (IDictionary<string, object>)model; object output; return !dictionaryModel.TryGetValue(propertyName, out output) ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, output); } /// <summary> /// Gets an IEnumerable of capture group values /// </summary> /// <param name="m">The match to use.</param> /// <param name="groupName">Group name containing the capture group.</param> /// <returns>IEnumerable of capture group values as strings.</returns> private static IEnumerable<string> GetCaptureGroupValues(Match m, string groupName) { return m.Groups[groupName].Captures.Cast<Capture>().Select(c => c.Value); } /// <summary> /// Gets a property value from a collection of nested parameter names /// </summary> /// <param name="model">The model containing properties.</param> /// <param name="parameters">A collection of nested parameters (e.g. User, Name</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was sucessful, Item2 being the value.</returns> private static Tuple<bool, object> GetPropertyValueFromParameterCollection(object model, IEnumerable<string> parameters) { if (parameters == null) { return new Tuple<bool, object>(true, model); } var currentObject = model; Tuple<bool, object> currentResult; foreach (var parameter in parameters) { currentResult = GetPropertyValue(currentObject, parameter); if (currentResult.Item1 == false) { return new Tuple<bool, object>(false, null); } currentObject = currentResult.Item2; } return new Tuple<bool, object>(true, currentObject); } /// <summary> /// Gets the predicate result for an If or IfNot block /// </summary> /// <param name="item">The item to evaluate</param> /// <param name="properties">Property list to evaluate</param> /// <returns>Bool representing the predicate result</returns> private static bool GetPredicateResult(object item, IEnumerable<string> properties) { var substitutionObject = GetPropertyValueFromParameterCollection(item, properties); if (substitutionObject.Item1 == false && properties.Last().StartsWith("Has")) { var newProperties = properties.Take(properties.Count() - 1).Concat(new[] { properties.Last().Substring(3) }); substitutionObject = GetPropertyValueFromParameterCollection(item, newProperties); return GetHasPredicateResultFromSubstitutionObject(substitutionObject.Item2); } if (substitutionObject.Item2 == null) { return false; } return GetPredicateResultFromSubstitutionObject(substitutionObject.Item2); } /// <summary> /// Returns the predicate result if the substitionObject is a valid bool /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <returns>Bool value of the substitutionObject, or false if unable to cast.</returns> private static bool GetPredicateResultFromSubstitutionObject(object substitutionObject) { var predicateResult = false; var substitutionBool = substitutionObject as bool?; if (substitutionBool != null) { predicateResult = substitutionBool.Value; } return predicateResult; } /// <summary> /// Returns the predicate result if the substitionObject is a valid ICollection /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <returns>Bool value of the whether the ICollection has items, or false if unable to cast.</returns> private static bool GetHasPredicateResultFromSubstitutionObject(object substitutionObject) { var predicateResult = false; var substitutionCollection = substitutionObject as ICollection; if (substitutionCollection != null) { predicateResult = substitutionCollection.Count != 0; } return predicateResult; } /// <summary> /// Performs single @Model.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>Template with @Model.PropertyName blocks expanded.</returns> private string PerformSingleSubstitutions(string template, object model) { return this.singleSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(model, properties); if (!substitution.Item1) { return "[ERR!]"; } return substitution.Item2 == null ? String.Empty : substitution.Item2.ToString(); }); } /// <summary> /// Performs @Each.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>Template with @Each.PropertyName blocks expanded.</returns> private string PerformEachSubstitutions(string template, object model) { return this.eachSubstitutionRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitutionObject = GetPropertyValueFromParameterCollection(model, properties); if (substitutionObject.Item1 == false) { return "[ERR!]"; } if (substitutionObject.Item2 == null) { return String.Empty; } var substitutionEnumerable = substitutionObject.Item2 as IEnumerable; if (substitutionEnumerable == null) { return "[ERR!]"; } var contents = m.Groups["Contents"].Value; var result = string.Empty; foreach (var item in substitutionEnumerable) { result += ReplaceCurrentMatch(contents, item); } return result; }); } /// <summary> /// Expand a @Current match inside an @Each iterator /// </summary> /// <param name="contents">Contents of the @Each block</param> /// <param name="item">Current item from the @Each enumerable</param> /// <returns>String result of the expansion of the @Each.</returns> private string ReplaceCurrentMatch(string contents, object item) { return this.eachItemSubstitutionRegEx.Replace( contents, eachMatch => { if (String.IsNullOrEmpty(eachMatch.Groups["ParameterName"].Value)) { return item.ToString(); } var properties = GetCaptureGroupValues(eachMatch, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(item, properties); if (!substitution.Item1) { return "[ERR!]"; } return substitution.Item2 == null ? String.Empty : substitution.Item2.ToString(); }); } /// <summary> /// Performs @If.PropertyName and @IfNot.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>Template with @If.PropertyName @IfNot.PropertyName blocks removed/expanded.</returns> private string PerformConditionalSubstitutions(string template, object model) { var result = template; result = this.conditionalSubstitutionRegEx.Replace( result, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var predicateResult = GetPredicateResult(model, properties); if (m.Groups["Not"].Value == "Not") { predicateResult = !predicateResult; } return predicateResult ? m.Groups["Contents"].Value : String.Empty; }); return result; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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 log4net; using MindTouch.Tasking; using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Dream.Test { using Yield = IEnumerator<IYield>; [TestFixture] public class ServiceExceptionMapTests { private DreamHostInfo _hostInfo; private DreamServiceInfo _serviceInfo; [TestFixtureSetUp] public void FixtureSetup() { _hostInfo = DreamTestHelper.CreateRandomPortHost(); _serviceInfo = DreamTestHelper.CreateService(_hostInfo, typeof(TestExceptionalService), "test"); } [TestFixtureTearDown] public void FixtureTeardown() { _hostInfo.Dispose(); } [Test] public void Can_throw_in_Start_with_exception_translators_in_place() { try { _serviceInfo = DreamTestHelper.CreateService(_hostInfo, typeof(TestExceptionalService), "throwsonstart", new XDoc("config").Elem("throw-on-start", true)); Assert.Fail("didn't throw on start"); } catch(Exception e) { Assert.IsTrue(e.Message.EndsWith("BadRequest: throwing in service start"),e.Message); } } [Test] public void Should_return_successfully() { var response = _serviceInfo.AtLocalHost.At("test").With("throwwhere", "never").GetAsync().Wait(); Assert.IsTrue(response.IsSuccessful); } [Test] public void Map_plain_exception_to_badrequest_in_main() { var response = _serviceInfo.AtLocalHost.At("test").With("throwwhere", "main").GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.BadRequest, response.Status); } [Test] public void Map_plain_exception_to_badrequest_in_prologue() { var response = _serviceInfo.AtLocalHost.At("test").With("throwwhere", "prologue").GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.BadRequest, response.Status); } [Test] public void Map_plain_exception_to_badrequest_in_epilogue() { var response = _serviceInfo.AtLocalHost.At("test").With("throwwhere", "epilogue").GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.BadRequest, response.Status); } [Test] public void Map_custom_exception_to_notacceptable_in_main() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "main") .With("throwwhat", "custom") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.NotAcceptable, response.Status); } [Test] public void Map_custom_exception_to_notacceptable_in_prologue() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "prologue") .With("throwwhat", "custom") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.NotAcceptable, response.Status); } [Test] public void Map_custom_exception_to_notacceptable_in_epilogue() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "epilogue") .With("throwwhat", "custom") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.NotAcceptable, response.Status); } [Test] public void DreamForbiddenException_in_main_does_not_hit_mapping() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "main") .With("throwwhat", "forbidden") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.Forbidden, response.Status); } [Test] public void DreamForbiddenException_in_prologue_does_not_hit_mapping() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "prologue") .With("throwwhat", "forbidden") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.Forbidden, response.Status); } [Test] public void DreamForbiddenException_in_epilogue_does_not_hit_mapping() { var response = _serviceInfo.AtLocalHost.At("test") .With("throwwhere", "epilogue") .With("throwwhat", "forbidden") .GetAsync().Wait(); Assert.IsFalse(response.IsSuccessful); Assert.AreEqual(DreamStatus.Forbidden, response.Status); } } public class CustomException : Exception { } [DreamService("TestExceptionalService", "Copyright (c) 200TestExceptionalService MindTouch, Inc.", Info = "", SID = new[] { "sid://mindtouch.com/TestExceptionalService" } )] public class TestExceptionalService : DreamService { //--- Class Fields --- private static readonly ILog _log = LogUtils.CreateLog(); [DreamFeature("*:test", "test")] public Yield Test(DreamContext context, DreamMessage request, Result<DreamMessage> response) { CheckThrow(context, "main"); response.Return(DreamMessage.Ok()); yield break; } private void CheckThrow(DreamContext context, string stage) { var throwWhere = context.GetParam("throwwhere", ""); var throwWhat = context.GetParam("throwwhat", ""); if(StringUtil.EqualsInvariantIgnoreCase(stage, throwWhere)) { if(string.IsNullOrEmpty(throwWhat)) { throw new Exception("plain old exception"); } if(StringUtil.EqualsInvariant("custom", throwWhat)) { throw new CustomException(); } if(StringUtil.EqualsInvariant("forbidden", throwWhat)) { throw new DreamForbiddenException("what? where?"); } } } protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); if( config["throw-on-start"].AsBool ?? false) { throw new Exception("throwing in service start"); } result.Return(); } public override DreamFeatureStage[] Prologues { get { return new[] { new DreamFeatureStage("prologue", Prologue, DreamAccess.Public), }; } } public override DreamFeatureStage[] Epilogues { get { return new[] { new DreamFeatureStage("epilogue", Epilogue, DreamAccess.Public), }; } } public override ExceptionTranslator[] ExceptionTranslators { get { return new ExceptionTranslator[] { MapCustomException, MapPlainException }; } } private DreamMessage MapPlainException(DreamContext context, Exception exception) { return DreamMessage.BadRequest(exception.Message); } private DreamMessage MapCustomException(DreamContext context, Exception exception) { if(typeof(CustomException).IsAssignableFrom(exception.GetType())) { return new DreamMessage(DreamStatus.NotAcceptable, null); } return null; } private Yield Prologue(DreamContext context, DreamMessage request, Result<DreamMessage> response) { CheckThrow(context, "prologue"); response.Return(request); yield break; } private Yield Epilogue(DreamContext context, DreamMessage request, Result<DreamMessage> response) { CheckThrow(context, "epilogue"); response.Return(request); yield break; } } }
// 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 OrUInt16() { var test = new SimpleBinaryOpTest__OrUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 SimpleBinaryOpTest__OrUInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static SimpleBinaryOpTest__OrUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__OrUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Or( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Or( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Or( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrUInt16(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { if ((ushort)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ushort)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. // 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.IO; namespace Siren.IO { /// <summary> /// Helper methods for encoding and decoding integer values. /// </summary> internal static class IntegerHelper { public const int MaxBytesVarInt16 = 3; public const int MaxBytesVarInt32 = 5; public const int MaxBytesVarInt64 = 10; public static int EncodeVarUInt16(byte[] data, ushort value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } // byte 2 data[index++] = (byte)value; return index; } public static int EncodeVarUInt32(byte[] data, uint value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } // last byte data[index++] = (byte)value; return index; } public static int EncodeVarUInt64(byte[] data, ulong value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 4 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 5 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 6 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 7 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 8 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } } } } } } // last byte data[index++] = (byte)value; return index; } public static ushort DecodeVarUInt16(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= raw << 14; } } index = i; return (ushort) result; } public static uint DecodeVarUInt32(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= raw << 28; } } } } index = i; return result; } public static ulong DecodeVarUInt64(byte[] data, ref int index) { var i = index; // byte 0 ulong result = data[i++]; if (0x80u <= result) { // byte 1 ulong raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= (raw & 0x7Fu) << 28; if (0x80u <= raw) { // byte 5 raw = data[i++]; result |= (raw & 0x7Fu) << 35; if (0x80u <= raw) { // byte 6 raw = data[i++]; result |= (raw & 0x7Fu) << 42; if (0x80u <= raw) { // byte 7 raw = data[i++]; result |= (raw & 0x7Fu) << 49; if (0x80u <= raw) { // byte 8 raw = data[i++]; result |= raw << 56; if (0x80u <= raw) { // byte 9 i++; } } } } } } } } } index = i; return result; } public static void EncodeVarUInt16(Stream stream, ushort value) { // byte 0 if (value >= 0x80) { stream.WriteByte((byte)(value | 0x80)); value >>= 7; // byte 1 if (value >= 0x80) { stream.WriteByte((byte)(value | 0x80)); value >>= 7; } } // byte 2 stream.WriteByte( (byte)value); } public static void EncodeVarUInt32(Stream stream, uint value) { // byte 0 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 1 if (value >= 0x80) { stream.WriteByte((byte)(value | 0x80)); value >>= 7; // byte 2 if (value >= 0x80) { stream.WriteByte((byte)(value | 0x80)); value >>= 7; // byte 3 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; } } } } // last byte stream.WriteByte( (byte)value); } public static void EncodeVarUInt64(Stream stream, ulong value) { // byte 0 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 1 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 2 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 3 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 4 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 5 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 6 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 7 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; // byte 8 if (value >= 0x80) { stream.WriteByte( (byte)(value | 0x80)); value >>= 7; } } } } } } } } } // last byte stream.WriteByte((byte)value); } public static ushort DecodeVarUInt16(Stream stream) { // byte 0 uint result = (uint)stream.ReadByte(); if (0x80u <= result) { // byte 1 uint raw = (uint)stream.ReadByte(); result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = (uint)stream.ReadByte(); result |= raw << 14; } } return (ushort)result; } public static uint DecodeVarUInt32(Stream stream) { // byte 0 uint result = (uint)stream.ReadByte(); if (0x80u <= result) { // byte 1 uint raw = (uint)stream.ReadByte(); result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = (uint)stream.ReadByte(); result |= raw << 28; } } } } return result; } public static ulong DecodeVarUInt64(Stream stream) { // byte 0 ulong result = (uint)stream.ReadByte(); if (0x80u <= result) { // byte 1 ulong raw = (uint)stream.ReadByte(); result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 28; if (0x80u <= raw) { // byte 5 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 35; if (0x80u <= raw) { // byte 6 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 42; if (0x80u <= raw) { // byte 7 raw = (uint)stream.ReadByte(); result |= (raw & 0x7Fu) << 49; if (0x80u <= raw) { // byte 8 raw = (uint)stream.ReadByte(); result |= raw << 56; if (0x80u <= raw) { // byte 9 } } } } } } } } } return result; } public static UInt16 EncodeZigzag(Int16 value) { return (UInt16)((value << 1) ^ (value >> (sizeof(Int16) * 8 - 1))); } public static UInt32 EncodeZigzag(Int32 value) { return (UInt32)((value << 1) ^ (value >> (sizeof(Int32) * 8 - 1))); } public static UInt64 EncodeZigzag(Int64 value) { return (UInt64)((value << 1) ^ (value >> (sizeof(Int64) * 8 - 1))); } public static Int16 DecodeZigzag(UInt16 value) { return (Int16)((value >> 1) ^ (-(value & 1))); } public static Int32 DecodeZigzag(UInt32 value) { return (Int32)((value >> 1) ^ (-(value & 1))); } public static Int64 DecodeZigzag(UInt64 value) { return (Int64)((value >> 1) ^ (UInt64)(-(Int64)(value & 1))); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Metadata { /// <summary> /// Reads metadata as defined byte the ECMA 335 CLI specification. /// </summary> public sealed partial class MetadataReader { private readonly MetadataReaderOptions _options; internal readonly MetadataStringDecoder utf8Decoder; internal readonly NamespaceCache namespaceCache; private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap; internal readonly MemoryBlock Block; // A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference). internal readonly int WinMDMscorlibRef; #region Constructors /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// </remarks> public unsafe MetadataReader(byte* metadata, int length) : this(metadata, length, MetadataReaderOptions.Default, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) : this(metadata, length, options, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder) { if (length <= 0) { throw new ArgumentOutOfRangeException("length"); } if (metadata == null) { throw new ArgumentNullException("metadata"); } if (utf8Decoder == null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } if (!(utf8Decoder.Encoding is UTF8Encoding)) { throw new ArgumentException(SR.MetadataStringDecoderEncodingMustBeUtf8, "utf8Decoder"); } if (!BitConverter.IsLittleEndian) { throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired); } this.Block = new MemoryBlock(metadata, length); _options = options; this.utf8Decoder = utf8Decoder; BlobReader memReader = new BlobReader(this.Block); this.ReadMetadataHeader(ref memReader); // storage header and stream headers: MemoryBlock metadataTableStream; var streamHeaders = this.ReadStreamHeaders(ref memReader); this.InitializeStreamReaders(ref this.Block, streamHeaders, out metadataTableStream); memReader = new BlobReader(metadataTableStream); int[] metadataTableRowCounts; this.ReadMetadataTableHeader(ref memReader, out metadataTableRowCounts); this.InitializeTableReaders(memReader.GetMemoryBlockAt(0, memReader.RemainingBytes), metadataTableRowCounts); // This previously could occur in obfuscated assemblies but a check was added to prevent // it getting to this point Debug.Assert(this.AssemblyTable.NumberOfRows <= 1); // Although the specification states that the module table will have exactly one row, // the native metadata reader would successfully read files containing more than one row. // Such files exist in the wild and may be produced by obfuscators. if (this.ModuleTable.NumberOfRows < 1) { throw new BadImageFormatException(string.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows)); } // read this.namespaceCache = new NamespaceCache(this); if (_metadataKind != MetadataKind.Ecma335) { this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); } } #endregion #region Metadata Headers private MetadataHeader _metadataHeader; private MetadataKind _metadataKind; private MetadataStreamKind _metadataStreamKind; internal StringStreamReader StringStream; internal BlobStreamReader BlobStream; internal GuidStreamReader GuidStream; internal UserStringStreamReader UserStringStream; /// <summary> /// True if the metadata stream has minimal delta format. Used for EnC. /// </summary> /// <remarks> /// The metadata stream has minimal delta format if "#JTD" stream is present. /// Minimal delta format uses large size (4B) when encoding table/heap references. /// The heaps in minimal delta only contain data of the delta, /// there is no padding at the beginning of the heaps that would align them /// with the original full metadata heaps. /// </remarks> internal bool IsMinimalDelta; /// <summary> /// Looks like this function reads beginning of the header described in /// Ecma-335 24.2.1 Metadata root /// </summary> private void ReadMetadataHeader(ref BlobReader memReader) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader) { throw new BadImageFormatException(SR.MetadataHeaderTooSmall); } _metadataHeader.Signature = memReader.ReadUInt32(); if (_metadataHeader.Signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(SR.MetadataSignature); } _metadataHeader.MajorVersion = memReader.ReadUInt16(); _metadataHeader.MinorVersion = memReader.ReadUInt16(); _metadataHeader.ExtraData = memReader.ReadUInt32(); _metadataHeader.VersionStringSize = memReader.ReadInt32(); if (memReader.RemainingBytes < _metadataHeader.VersionStringSize) { throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } int numberOfBytesRead; _metadataHeader.VersionString = memReader.GetMemoryBlockAt(0, _metadataHeader.VersionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0'); memReader.SkipBytes(_metadataHeader.VersionStringSize); _metadataKind = GetMetadataKind(_metadataHeader.VersionString); } private MetadataKind GetMetadataKind(string versionString) { // Treat metadata as CLI raw metadata if the client doesn't want to see projections. if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0) { return MetadataKind.Ecma335; } if (!versionString.Contains("WindowsRuntime")) { return MetadataKind.Ecma335; } else if (versionString.Contains("CLR")) { return MetadataKind.ManagedWindowsMetadata; } else { return MetadataKind.WindowsMetadata; } } /// <summary> /// Reads stream headers described in Ecma-335 24.2.2 Stream header /// </summary> private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); int streamCount = memReader.ReadInt16(); var streamHeaders = new StreamHeader[streamCount]; for (int i = 0; i < streamHeaders.Length; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(SR.StreamHeaderTooSmall); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadInt32(); streamHeaders[i].Name = memReader.ReadUtf8NullTerminated(); bool aligned = memReader.TryAlign(4); if (!aligned || memReader.RemainingBytes == 0) { throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName); } } return streamHeaders; } private void InitializeStreamReaders(ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MemoryBlock metadataTableStream) { metadataTableStream = default(MemoryBlock); foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream); } this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream); } this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } _metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } _metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } // the content of the stream is ignored this.IsMinimalDelta = true; break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && _metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException(SR.InvalidMetadataStreamFormat); } } #endregion #region Tables and Heaps private MetadataTableHeader _MetadataTableHeader; /// <summary> /// A row count for each possible table. May be indexed by <see cref="TableIndex"/>. /// </summary> internal int[] TableRowCounts; internal ModuleTableReader ModuleTable; internal TypeRefTableReader TypeRefTable; internal TypeDefTableReader TypeDefTable; internal FieldPtrTableReader FieldPtrTable; internal FieldTableReader FieldTable; internal MethodPtrTableReader MethodPtrTable; internal MethodTableReader MethodDefTable; internal ParamPtrTableReader ParamPtrTable; internal ParamTableReader ParamTable; internal InterfaceImplTableReader InterfaceImplTable; internal MemberRefTableReader MemberRefTable; internal ConstantTableReader ConstantTable; internal CustomAttributeTableReader CustomAttributeTable; internal FieldMarshalTableReader FieldMarshalTable; internal DeclSecurityTableReader DeclSecurityTable; internal ClassLayoutTableReader ClassLayoutTable; internal FieldLayoutTableReader FieldLayoutTable; internal StandAloneSigTableReader StandAloneSigTable; internal EventMapTableReader EventMapTable; internal EventPtrTableReader EventPtrTable; internal EventTableReader EventTable; internal PropertyMapTableReader PropertyMapTable; internal PropertyPtrTableReader PropertyPtrTable; internal PropertyTableReader PropertyTable; internal MethodSemanticsTableReader MethodSemanticsTable; internal MethodImplTableReader MethodImplTable; internal ModuleRefTableReader ModuleRefTable; internal TypeSpecTableReader TypeSpecTable; internal ImplMapTableReader ImplMapTable; internal FieldRVATableReader FieldRvaTable; internal EnCLogTableReader EncLogTable; internal EnCMapTableReader EncMapTable; internal AssemblyTableReader AssemblyTable; internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused internal AssemblyOSTableReader AssemblyOSTable; // unused internal AssemblyRefTableReader AssemblyRefTable; internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused internal FileTableReader FileTable; internal ExportedTypeTableReader ExportedTypeTable; internal ManifestResourceTableReader ManifestResourceTable; internal NestedClassTableReader NestedClassTable; internal GenericParamTableReader GenericParamTable; internal MethodSpecTableReader MethodSpecTable; internal GenericParamConstraintTableReader GenericParamConstraintTable; private void ReadMetadataTableHeader(ref BlobReader memReader, out int[] metadataTableRowCounts) { if (memReader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall); } _MetadataTableHeader.Reserved = memReader.ReadUInt32(); _MetadataTableHeader.MajorVersion = memReader.ReadByte(); _MetadataTableHeader.MinorVersion = memReader.ReadByte(); _MetadataTableHeader.HeapSizeFlags = (HeapSizeFlag)memReader.ReadByte(); _MetadataTableHeader.RowId = memReader.ReadByte(); _MetadataTableHeader.ValidTables = (TableMask)memReader.ReadUInt64(); _MetadataTableHeader.SortedTables = (TableMask)memReader.ReadUInt64(); ulong presentTables = (ulong)_MetadataTableHeader.ValidTables; // According to ECMA-335, MajorVersion and MinorVersion have fixed values and, // based on recommendation in 24.1 Fixed fields: When writing these fields it // is best that they be set to the value indicated, on reading they should be ignored.? // we will not be checking version values. We will continue checking that the set of // present tables is within the set we understand. ulong validTables = (ulong)TableMask.V2_0_TablesMask; if ((presentTables & ~validTables) != 0) { throw new BadImageFormatException(string.Format(SR.UnknownTables, presentTables)); } if (_metadataStreamKind == MetadataStreamKind.Compressed) { // In general Ptr tables and EnC tables are not allowed in a compressed stream. // However when asked for a snapshot of the current metadata after an EnC change has been applied // the CLR includes the EnCLog table into the snapshot. We need to be able to read the image, // so we'll allow the table here but pretend it's empty later. if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0) { throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream); } } int numberOfTables = _MetadataTableHeader.GetNumberOfTablesPresent(); if (memReader.RemainingBytes < numberOfTables * sizeof(int)) { throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall); } var rowCounts = new int[numberOfTables]; for (int i = 0; i < rowCounts.Length; i++) { uint rowCount = memReader.ReadUInt32(); if (rowCount > TokenTypeIds.RIDMask) { throw new BadImageFormatException(string.Format(SR.InvalidRowCount, rowCount)); } rowCounts[i] = (int)rowCount; } metadataTableRowCounts = rowCounts; } private const int SmallIndexSize = 2; private const int LargeIndexSize = 4; private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, int[] compressedRowCounts) { // Only sizes of tables present in metadata are recorded in rowCountCompressedArray. // This array contains a slot for each possible table, not just those that are present in the metadata. int[] rowCounts = new int[TableIndexExtensions.Count]; // Size of reference tags in each table. int[] referenceSizes = new int[TableIndexExtensions.Count]; ulong validTables = (ulong)_MetadataTableHeader.ValidTables; int compressedRowCountIndex = 0; for (int i = 0; i < TableIndexExtensions.Count; i++) { bool fitsSmall; if ((validTables & 1UL) != 0) { int rowCount = compressedRowCounts[compressedRowCountIndex++]; rowCounts[i] = rowCount; fitsSmall = rowCount < MetadataStreamConstants.LargeTableRowCount; } else { fitsSmall = true; } referenceSizes[i] = (fitsSmall && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize; validTables >>= 1; } this.TableRowCounts = rowCounts; // Compute ref sizes for tables that can have pointer tables for it int fieldRefSize = referenceSizes[(int)TableIndex.FieldPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Field]; int methodRefSize = referenceSizes[(int)TableIndex.MethodPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.MethodDef]; int paramRefSize = referenceSizes[(int)TableIndex.ParamPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Param]; int eventRefSize = referenceSizes[(int)TableIndex.EventPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Event]; int propertyRefSize = referenceSizes[(int)TableIndex.PropertyPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Property]; // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (_MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.StringHeapLarge) == HeapSizeFlag.StringHeapLarge ? LargeIndexSize : SmallIndexSize; int guidHeapRefSize = (_MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.GuidHeapLarge) == HeapSizeFlag.GuidHeapLarge ? LargeIndexSize : SmallIndexSize; int blobHeapRefSize = (_MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.BlobHeapLarge) == HeapSizeFlag.BlobHeapLarge ? LargeIndexSize : SmallIndexSize; // Populate the Table blocks int totalRequiredSize = 0; this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleTable.Block.Length; this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeRefTable.Block.Length; this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeDefTable.Block.Length; this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldPtrTable.Block.Length; this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldTable.Block.Length; this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], referenceSizes[(int)TableIndex.MethodDef], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodPtrTable.Block.Length; this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDefTable.Block.Length; this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], referenceSizes[(int)TableIndex.Param], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamPtrTable.Block.Length; this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamTable.Block.Length; this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), referenceSizes[(int)TableIndex.TypeDef], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.InterfaceImplTable.Block.Length; this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MemberRefTable.Block.Length; this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ConstantTable.Block.Length; this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomAttributeTable.Block.Length; this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldMarshalTable.Block.Length; this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DeclSecurityTable.Block.Length; this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ClassLayoutTable.Block.Length; this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldLayoutTable.Block.Length; this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StandAloneSigTable.Block.Length; this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], referenceSizes[(int)TableIndex.TypeDef], eventRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventMapTable.Block.Length; this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], referenceSizes[(int)TableIndex.Event], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventPtrTable.Block.Length; this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventTable.Block.Length; this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], referenceSizes[(int)TableIndex.TypeDef], propertyRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyMapTable.Block.Length; this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], referenceSizes[(int)TableIndex.Property], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyPtrTable.Block.Length; this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyTable.Block.Length; this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), referenceSizes[(int)TableIndex.MethodDef], hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSemanticsTable.Block.Length; this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), referenceSizes[(int)TableIndex.TypeDef], methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodImplTable.Block.Length; this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleRefTable.Block.Length; this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeSpecTable.Block.Length; this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), referenceSizes[(int)TableIndex.ModuleRef], memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImplMapTable.Block.Length; this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldRvaTable.Block.Length; this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind); totalRequiredSize += this.EncLogTable.Block.Length; this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EncMapTable.Block.Length; this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyTable.Block.Length; this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyProcessorTable.Block.Length; this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyOSTable.Block.Length; this.AssemblyRefTable = new AssemblyRefTableReader((int)rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind); totalRequiredSize += this.AssemblyRefTable.Block.Length; this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length; this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefOSTable.Block.Length; this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FileTable.Block.Length; this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ExportedTypeTable.Block.Length; this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ManifestResourceTable.Block.Length; this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.NestedClassTable.Block.Length; this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamTable.Block.Length; this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSpecTable.Block.Length; this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), referenceSizes[(int)TableIndex.GenericParam], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamConstraintTable.Block.Length; if (totalRequiredSize > metadataTablesMemoryBlock.Length) { throw new BadImageFormatException(SR.MetadataTablesTooSmall); } } private int ComputeCodedTokenSize(int largeRowSize, int[] rowCountArray, TableMask tablesReferenced) { if (IsMinimalDelta) { return LargeIndexSize; } bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++) { if ((tablesReferencedMask & 1UL) != 0) { isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCountArray[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize; } private bool IsDeclaredSorted(TableMask index) { return (_MetadataTableHeader.SortedTables & index) != 0; } #endregion #region Helpers // internal for testing internal NamespaceCache NamespaceCache { get { return namespaceCache; } } internal bool UseFieldPtrTable { get { return this.FieldPtrTable.NumberOfRows > 0; } } internal bool UseMethodPtrTable { get { return this.MethodPtrTable.NumberOfRows > 0; } } internal bool UseParamPtrTable { get { return this.ParamPtrTable.NumberOfRows > 0; } } internal bool UseEventPtrTable { get { return this.EventPtrTable.NumberOfRows > 0; } } internal bool UsePropertyPtrTable { get { return this.PropertyPtrTable.NumberOfRows > 0; } } internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) { int typeDefRowId = typeDef.RowId; firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId); if (firstFieldRowId == 0) { firstFieldRowId = 1; lastFieldRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows; } else { lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1; } } internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) { int typeDefRowId = typeDef.RowId; firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId); if (firstMethodRowId == 0) { firstMethodRowId = 1; lastMethodRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows; } else { lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1; } } internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) { int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef); if (eventMapRowId == 0) { firstEventRowId = 1; lastEventRowId = 0; return; } firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId); if (eventMapRowId == this.EventMapTable.NumberOfRows) { lastEventRowId = (int)(this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows); } else { lastEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1; } } internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) { int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef); if (propertyMapRowId == 0) { firstPropertyRowId = 1; lastPropertyRowId = 0; return; } firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId); if (propertyMapRowId == this.PropertyMapTable.NumberOfRows) { lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows; } else { lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1; } } internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) { int rid = methodDef.RowId; firstParamRowId = this.MethodDefTable.GetParamStart(rid); if (firstParamRowId == 0) { firstParamRowId = 1; lastParamRowId = 0; } else if (rid == this.MethodDefTable.NumberOfRows) { lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows); } else { lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1; } } #endregion #region Public APIs public MetadataReaderOptions Options { get { return _options; } } public string MetadataVersion { get { return _metadataHeader.VersionString; } } public MetadataKind MetadataKind { get { return _metadataKind; } } public MetadataStringComparer StringComparer { get { return new MetadataStringComparer(this); } } public bool IsAssembly { get { return this.AssemblyTable.NumberOfRows == 1; } } public AssemblyReferenceHandleCollection AssemblyReferences { get { return new AssemblyReferenceHandleCollection(this); } } public TypeDefinitionHandleCollection TypeDefinitions { get { return new TypeDefinitionHandleCollection((int)TypeDefTable.NumberOfRows); } } public TypeReferenceHandleCollection TypeReferences { get { return new TypeReferenceHandleCollection((int)TypeRefTable.NumberOfRows); } } public CustomAttributeHandleCollection CustomAttributes { get { return new CustomAttributeHandleCollection(this); } } public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes { get { return new DeclarativeSecurityAttributeHandleCollection(this); } } public MemberReferenceHandleCollection MemberReferences { get { return new MemberReferenceHandleCollection((int)MemberRefTable.NumberOfRows); } } public ManifestResourceHandleCollection ManifestResources { get { return new ManifestResourceHandleCollection((int)ManifestResourceTable.NumberOfRows); } } public AssemblyFileHandleCollection AssemblyFiles { get { return new AssemblyFileHandleCollection((int)FileTable.NumberOfRows); } } public ExportedTypeHandleCollection ExportedTypes { get { return new ExportedTypeHandleCollection((int)ExportedTypeTable.NumberOfRows); } } public MethodDefinitionHandleCollection MethodDefinitions { get { return new MethodDefinitionHandleCollection(this); } } public FieldDefinitionHandleCollection FieldDefinitions { get { return new FieldDefinitionHandleCollection(this); } } public EventDefinitionHandleCollection EventDefinitions { get { return new EventDefinitionHandleCollection(this); } } public PropertyDefinitionHandleCollection PropertyDefinitions { get { return new PropertyDefinitionHandleCollection(this); } } public AssemblyDefinition GetAssemblyDefinition() { if (!IsAssembly) { throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly); } return new AssemblyDefinition(this); } public string GetString(StringHandle handle) { return StringStream.GetString(handle, utf8Decoder); } public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringStream.GetString(handle.GetFullName(), utf8Decoder); } return namespaceCache.GetFullName(handle); } public byte[] GetBlobBytes(BlobHandle handle) { return BlobStream.GetBytes(handle); } public ImmutableArray<byte> GetBlobContent(BlobHandle handle) { // TODO: We can skip a copy for virtual blobs. byte[] bytes = GetBlobBytes(handle); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetBlobReader(BlobHandle handle) { return BlobStream.GetBlobReader(handle); } public string GetUserString(UserStringHandle handle) { return UserStringStream.GetString(handle); } public Guid GetGuid(GuidHandle handle) { return GuidStream.GetGuid(handle); } public ModuleDefinition GetModuleDefinition() { return new ModuleDefinition(this); } public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) { return new AssemblyReference(this, handle.Value); } public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); } public NamespaceDefinition GetNamespaceDefinitionRoot() { NamespaceData data = namespaceCache.GetRootNamespace(); return new NamespaceDefinition(data); } public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = namespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); } private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeDefTreatmentAndRowId(handle); } public TypeReference GetTypeReference(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); } private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeRefTreatmentAndRowId(handle); } public ExportedType GetExportedType(ExportedTypeHandle handle) { return new ExportedType(this, handle.RowId); } public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) { Debug.Assert(!handle.IsNil); return new CustomAttributeHandleCollection(this, handle); } public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); } private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId); } public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new DeclarativeSecurityAttribute(this, handle.RowId); } public Constant GetConstant(ConstantHandle handle) { return new Constant(this, handle.RowId); } public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); } private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMethodDefTreatmentAndRowId(handle); } public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); } private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateFieldDefTreatmentAndRowId(handle); } public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) { return new PropertyDefinition(this, handle); } public EventDefinition GetEventDefinition(EventDefinitionHandle handle) { return new EventDefinition(this, handle); } public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) { return new MethodImplementation(this, handle); } public MemberReference GetMemberReference(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); } private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMemberRefTreatmentAndRowId(handle); } public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) { return new MethodSpecification(this, handle); } public Parameter GetParameter(ParameterHandle handle) { return new Parameter(this, handle); } public GenericParameter GetGenericParameter(GenericParameterHandle handle) { return new GenericParameter(this, handle); } public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) { return new GenericParameterConstraint(this, handle); } public ManifestResource GetManifestResource(ManifestResourceHandle handle) { return new ManifestResource(this, handle); } public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) { return new AssemblyFile(this, handle); } public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) { return new StandaloneSignature(this, handle); } public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) { return new TypeSpecification(this, handle); } public ModuleReference GetModuleReference(ModuleReferenceHandle handle) { return new ModuleReference(this, handle); } public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) { return new InterfaceImplementation(this, handle); } internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) { int methodRowId; if (UseMethodPtrTable) { methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId); } else { methodRowId = methodDef.RowId; } return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows); } internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) { int fieldRowId; if (UseFieldPtrTable) { fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId); } else { fieldRowId = fieldDef.RowId; } return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows); } #endregion #region Nested Types private void InitializeNestedTypesMap() { var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>(); int numberOfNestedTypes = NestedClassTable.NumberOfRows; ImmutableArray<TypeDefinitionHandle>.Builder builder = null; TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle); for (int i = 1; i <= numberOfNestedTypes; i++) { TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); Debug.Assert(!enclosingClass.IsNil); if (enclosingClass != previousEnclosingClass) { if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder)) { builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); groupedNestedTypes.Add(enclosingClass, builder); } previousEnclosingClass = enclosingClass; } else { Debug.Assert(builder == groupedNestedTypes[enclosingClass]); } builder.Add(NestedClassTable.GetNestedClass(i)); } var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>(); foreach (var group in groupedNestedTypes) { nestedTypesMap.Add(group.Key, group.Value.ToImmutable()); } _lazyNestedTypesMap = nestedTypesMap; } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef) { if (_lazyNestedTypesMap == null) { InitializeNestedTypesMap(); } ImmutableArray<TypeDefinitionHandle> nestedTypes; if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes)) { return nestedTypes; } return ImmutableArray<TypeDefinitionHandle>.Empty; } #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 class encapsulates security decisions about an application. // namespace System.Security.Policy { using System.Collections; using System.Collections.Generic; #if FEATURE_CLICKONCE using System.Deployment.Internal.Isolation; using System.Deployment.Internal.Isolation.Manifest; #endif using System.Globalization; using System.IO; using System.Runtime.InteropServices; #if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; #endif // FEATURE_SERIALIZATION using System.Runtime.Versioning; using System.Security.Permissions; using System.Security.Util; using System.Text; using System.Threading; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public enum ApplicationVersionMatch { MatchExactVersion, MatchAllVersions } [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable { #if FEATURE_CLICKONCE private ApplicationIdentity m_appId; private bool m_appTrustedToRun; private bool m_persist; private object m_extraInfo; private SecurityElement m_elExtraInfo; #endif private PolicyStatement m_psDefaultGrant; private IList<StrongName> m_fullTrustAssemblies; // Permission special flags for the default grant set in this ApplicationTrust. This should be // updated in sync with any updates to the default grant set. // // In the general case, these values cannot be trusted - we only store a reference to the // DefaultGrantSet, and return the reference directly, which means that code can update the // permission set without our knowledge. That would lead to the flags getting out of sync with the // grant set. // // However, we only care about these flags when we're creating a homogenous AppDomain, and in that // case we control the ApplicationTrust object end-to-end, and know that the permission set will not // change after the flags are calculated. [NonSerialized] private int m_grantSetSpecialFlags; #if FEATURE_CLICKONCE public ApplicationTrust (ApplicationIdentity applicationIdentity) : this () { ApplicationIdentity = applicationIdentity; } #endif public ApplicationTrust () : this (new PermissionSet(PermissionState.None)) { } internal ApplicationTrust (PermissionSet defaultGrantSet) { InitDefaultGrantSet(defaultGrantSet); m_fullTrustAssemblies = new List<StrongName>().AsReadOnly(); } public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable<StrongName> fullTrustAssemblies) { if (fullTrustAssemblies == null) { throw new ArgumentNullException("fullTrustAssemblies"); } InitDefaultGrantSet(defaultGrantSet); List<StrongName> fullTrustList = new List<StrongName>(); foreach (StrongName strongName in fullTrustAssemblies) { if (strongName == null) { throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), "fullTrustAssemblies"); } fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version)); } m_fullTrustAssemblies = fullTrustList.AsReadOnly(); } // Sets up the default grant set for all constructors. Extracted to avoid the cost of // IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR) private void InitDefaultGrantSet(PermissionSet defaultGrantSet) { if (defaultGrantSet == null) { throw new ArgumentNullException("defaultGrantSet"); } // Creating a PolicyStatement copies the incoming permission set, so we don't have to worry // about the PermissionSet parameter changing underneath us after we've calculated the // permisison flags in the DefaultGrantSet setter. DefaultGrantSet = new PolicyStatement(defaultGrantSet); } #if FEATURE_CLICKONCE public ApplicationIdentity ApplicationIdentity { get { return m_appId; } set { if (value == null) throw new ArgumentNullException("value", Environment.GetResourceString("Argument_InvalidAppId")); Contract.EndContractBlock(); m_appId = value; } } #endif public PolicyStatement DefaultGrantSet { get { if (m_psDefaultGrant == null) return new PolicyStatement(new PermissionSet(PermissionState.None)); return m_psDefaultGrant; } set { if (value == null) { m_psDefaultGrant = null; m_grantSetSpecialFlags = 0; } else { m_psDefaultGrant = value; m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(m_psDefaultGrant.PermissionSet, null); } } } public IList<StrongName> FullTrustAssemblies { get { return m_fullTrustAssemblies; } } #if FEATURE_CLICKONCE public bool IsApplicationTrustedToRun { get { return m_appTrustedToRun; } set { m_appTrustedToRun = value; } } public bool Persist { get { return m_persist; } set { m_persist = value; } } public object ExtraInfo { get { if (m_elExtraInfo != null) { m_extraInfo = ObjectFromXml(m_elExtraInfo); m_elExtraInfo = null; } return m_extraInfo; } set { m_elExtraInfo = null; m_extraInfo = value; } } #endif //FEATURE_CLICKONCE #if FEATURE_CAS_POLICY public SecurityElement ToXml () { SecurityElement elRoot = new SecurityElement("ApplicationTrust"); elRoot.AddAttribute("version", "1"); #if FEATURE_CLICKONCE if (m_appId != null) { elRoot.AddAttribute("FullName", SecurityElement.Escape(m_appId.FullName)); } if (m_appTrustedToRun) { elRoot.AddAttribute("TrustedToRun", "true"); } if (m_persist) { elRoot.AddAttribute("Persist", "true"); } #endif // FEATURE_CLICKONCE if (m_psDefaultGrant != null) { SecurityElement elDefaultGrant = new SecurityElement("DefaultGrant"); elDefaultGrant.AddChild(m_psDefaultGrant.ToXml()); elRoot.AddChild(elDefaultGrant); } if (m_fullTrustAssemblies.Count > 0) { SecurityElement elFullTrustAssemblies = new SecurityElement("FullTrustAssemblies"); foreach (StrongName fullTrustAssembly in m_fullTrustAssemblies) { elFullTrustAssemblies.AddChild(fullTrustAssembly.ToXml()); } elRoot.AddChild(elFullTrustAssemblies); } #if FEATURE_CLICKONCE if (ExtraInfo != null) { elRoot.AddChild(ObjectToXml("ExtraInfo", ExtraInfo)); } #endif // FEATURE_CLICKONCE return elRoot; } public void FromXml (SecurityElement element) { if (element == null) throw new ArgumentNullException("element"); if (String.Compare(element.Tag, "ApplicationTrust", StringComparison.Ordinal) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); #if FEATURE_CLICKONCE m_appTrustedToRun = false; string isAppTrustedToRun = element.Attribute("TrustedToRun"); if (isAppTrustedToRun != null && String.Compare(isAppTrustedToRun, "true", StringComparison.Ordinal) == 0) { m_appTrustedToRun = true; } m_persist = false; string persist = element.Attribute("Persist"); if (persist != null && String.Compare(persist, "true", StringComparison.Ordinal) == 0) { m_persist = true; } m_appId = null; string fullName = element.Attribute("FullName"); if (fullName != null && fullName.Length > 0) { m_appId = new ApplicationIdentity(fullName); } #endif // FEATURE_CLICKONCE m_psDefaultGrant = null; m_grantSetSpecialFlags = 0; SecurityElement elDefaultGrant = element.SearchForChildByTag("DefaultGrant"); if (elDefaultGrant != null) { SecurityElement elDefaultGrantPS = elDefaultGrant.SearchForChildByTag("PolicyStatement"); if (elDefaultGrantPS != null) { PolicyStatement ps = new PolicyStatement(null); ps.FromXml(elDefaultGrantPS); m_psDefaultGrant = ps; m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(ps.PermissionSet, null); } } List<StrongName> fullTrustAssemblies = new List<StrongName>(); SecurityElement elFullTrustAssemblies = element.SearchForChildByTag("FullTrustAssemblies"); if (elFullTrustAssemblies != null && elFullTrustAssemblies.InternalChildren != null) { IEnumerator enumerator = elFullTrustAssemblies.Children.GetEnumerator(); while (enumerator.MoveNext()) { StrongName fullTrustAssembly = new StrongName(); fullTrustAssembly.FromXml(enumerator.Current as SecurityElement); fullTrustAssemblies.Add(fullTrustAssembly); } } m_fullTrustAssemblies = fullTrustAssemblies.AsReadOnly(); #if FEATURE_CLICKONCE m_elExtraInfo = element.SearchForChildByTag("ExtraInfo"); #endif // FEATURE_CLICKONCE } #if FEATURE_CLICKONCE private static SecurityElement ObjectToXml (string tag, Object obj) { BCLDebug.Assert(obj != null, "You need to pass in an object"); ISecurityEncodable encodableObj = obj as ISecurityEncodable; SecurityElement elObject; if (encodableObj != null) { elObject = encodableObj.ToXml(); if (!elObject.Tag.Equals(tag)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); } MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, obj); byte[] array = stream.ToArray(); elObject = new SecurityElement(tag); elObject.AddAttribute("Data", Hex.EncodeHexString(array)); return elObject; } private static Object ObjectFromXml (SecurityElement elObject) { BCLDebug.Assert(elObject != null, "You need to pass in a security element"); if (elObject.Attribute("class") != null) { ISecurityEncodable encodableObj = XMLUtil.CreateCodeGroup(elObject) as ISecurityEncodable; if (encodableObj != null) { encodableObj.FromXml(elObject); return encodableObj; } } string objectData = elObject.Attribute("Data"); MemoryStream stream = new MemoryStream(Hex.DecodeHexString(objectData)); BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(stream); } #endif // FEATURE_CLICKONCE #endif // FEATURE_CAS_POLICY #pragma warning disable 618 [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] #pragma warning restore 618 [SecuritySafeCritical] public override EvidenceBase Clone() { return base.Clone(); } } #if FEATURE_CLICKONCE [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] public sealed class ApplicationTrustCollection : ICollection { private const string ApplicationTrustProperty = "ApplicationTrust"; private const string InstallerIdentifier = "{60051b8f-4f12-400a-8e50-dd05ebd438d1}"; private static Guid ClrPropertySet = new Guid("c989bb7a-8385-4715-98cf-a741a8edb823"); // The CLR specific constant install reference. private static object s_installReference = null; private static StoreApplicationReference InstallReference { get { if (s_installReference == null) { Interlocked.CompareExchange(ref s_installReference, new StoreApplicationReference( IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, null), null); } return (StoreApplicationReference) s_installReference; } } private object m_appTrusts = null; private ArrayList AppTrusts { [System.Security.SecurityCritical] // auto-generated get { if (m_appTrusts == null) { ArrayList appTrusts = new ArrayList(); if (m_storeBounded) { RefreshStorePointer(); // enumerate the user store and populate the collection StoreDeploymentMetadataEnumeration deplEnum = m_pStore.EnumInstallerDeployments(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, null); foreach (IDefinitionAppId defAppId in deplEnum) { StoreDeploymentMetadataPropertyEnumeration metadataEnum = m_pStore.EnumInstallerDeploymentProperties(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, defAppId); foreach (StoreOperationMetadataProperty appTrustProperty in metadataEnum) { string appTrustXml = appTrustProperty.Value; if (appTrustXml != null && appTrustXml.Length > 0) { SecurityElement seTrust = SecurityElement.FromString(appTrustXml); ApplicationTrust appTrust = new ApplicationTrust(); appTrust.FromXml(seTrust); appTrusts.Add(appTrust); } } } } Interlocked.CompareExchange(ref m_appTrusts, appTrusts, null); } return m_appTrusts as ArrayList; } } private bool m_storeBounded = false; private Store m_pStore = null; // Component store interface pointer. // Only internal constructors are exposed. [System.Security.SecurityCritical] // auto-generated internal ApplicationTrustCollection () : this(false) {} internal ApplicationTrustCollection (bool storeBounded) { m_storeBounded = storeBounded; } [System.Security.SecurityCritical] // auto-generated private void RefreshStorePointer () { // Refresh store pointer. if (m_pStore != null) Marshal.ReleaseComObject(m_pStore.InternalStore); m_pStore = IsolationInterop.GetUserStore(); } public int Count { [System.Security.SecuritySafeCritical] // overrides public transparent member get { return AppTrusts.Count; } } public ApplicationTrust this[int index] { [System.Security.SecurityCritical] // auto-generated get { return AppTrusts[index] as ApplicationTrust; } } public ApplicationTrust this[string appFullName] { [System.Security.SecurityCritical] // auto-generated get { ApplicationIdentity identity = new ApplicationIdentity(appFullName); ApplicationTrustCollection appTrusts = Find(identity, ApplicationVersionMatch.MatchExactVersion); if (appTrusts.Count > 0) return appTrusts[0]; return null; } } [System.Security.SecurityCritical] // auto-generated private void CommitApplicationTrust(ApplicationIdentity applicationIdentity, string trustXml) { StoreOperationMetadataProperty[] properties = new StoreOperationMetadataProperty[] { new StoreOperationMetadataProperty(ClrPropertySet, ApplicationTrustProperty, trustXml) }; IEnumDefinitionIdentity idenum = applicationIdentity.Identity.EnumAppPath(); IDefinitionIdentity[] asbId = new IDefinitionIdentity[1]; IDefinitionIdentity deplId = null; if (idenum.Next(1, asbId) == 1) deplId = asbId[0]; IDefinitionAppId defAppId = IsolationInterop.AppIdAuthority.CreateDefinition(); defAppId.SetAppPath(1, new IDefinitionIdentity[] {deplId}); defAppId.put_Codebase(applicationIdentity.CodeBase); using (StoreTransaction storeTxn = new StoreTransaction()) { storeTxn.Add(new StoreOperationSetDeploymentMetadata(defAppId, InstallReference, properties)); RefreshStorePointer(); m_pStore.Transact(storeTxn.Operations); } m_appTrusts = null; // reset the app trusts in the collection. } [System.Security.SecurityCritical] // auto-generated public int Add (ApplicationTrust trust) { if (trust == null) throw new ArgumentNullException("trust"); if (trust.ApplicationIdentity == null) throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity")); Contract.EndContractBlock(); // Add the trust decision of the application to the fusion store. if (m_storeBounded) { CommitApplicationTrust(trust.ApplicationIdentity, trust.ToXml().ToString()); return -1; } else { return AppTrusts.Add(trust); } } [System.Security.SecurityCritical] // auto-generated public void AddRange (ApplicationTrust[] trusts) { if (trusts == null) throw new ArgumentNullException("trusts"); Contract.EndContractBlock(); int i=0; try { for (; i<trusts.Length; i++) { Add(trusts[i]); } } catch { for (int j=0; j<i; j++) { Remove(trusts[j]); } throw; } } [System.Security.SecurityCritical] // auto-generated public void AddRange (ApplicationTrustCollection trusts) { if (trusts == null) throw new ArgumentNullException("trusts"); Contract.EndContractBlock(); int i = 0; try { foreach (ApplicationTrust trust in trusts) { Add(trust); i++; } } catch { for (int j=0; j<i; j++) { Remove(trusts[j]); } throw; } } [System.Security.SecurityCritical] // auto-generated public ApplicationTrustCollection Find (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) { ApplicationTrustCollection collection = new ApplicationTrustCollection(false); foreach (ApplicationTrust trust in this) { if (CmsUtils.CompareIdentities(trust.ApplicationIdentity, applicationIdentity, versionMatch)) collection.Add(trust); } return collection; } [System.Security.SecurityCritical] // auto-generated public void Remove (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) { ApplicationTrustCollection collection = Find(applicationIdentity, versionMatch); RemoveRange(collection); } [System.Security.SecurityCritical] // auto-generated public void Remove (ApplicationTrust trust) { if (trust == null) throw new ArgumentNullException("trust"); if (trust.ApplicationIdentity == null) throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity")); Contract.EndContractBlock(); // Remove the trust decision of the application from the fusion store. if (m_storeBounded) { CommitApplicationTrust(trust.ApplicationIdentity, null); } else { AppTrusts.Remove(trust); } } [System.Security.SecurityCritical] // auto-generated public void RemoveRange (ApplicationTrust[] trusts) { if (trusts == null) throw new ArgumentNullException("trusts"); Contract.EndContractBlock(); int i=0; try { for (; i<trusts.Length; i++) { Remove(trusts[i]); } } catch { for (int j=0; j<i; j++) { Add(trusts[j]); } throw; } } [System.Security.SecurityCritical] // auto-generated public void RemoveRange (ApplicationTrustCollection trusts) { if (trusts == null) throw new ArgumentNullException("trusts"); Contract.EndContractBlock(); int i = 0; try { foreach (ApplicationTrust trust in trusts) { Remove(trust); i++; } } catch { for (int j=0; j<i; j++) { Add(trusts[j]); } throw; } } [System.Security.SecurityCritical] // auto-generated public void Clear() { // remove all trust decisions in the collection. ArrayList trusts = this.AppTrusts; if (m_storeBounded) { foreach (ApplicationTrust trust in trusts) { if (trust.ApplicationIdentity == null) throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity")); // Remove the trust decision of the application from the fusion store. CommitApplicationTrust(trust.ApplicationIdentity, null); } } trusts.Clear(); } public ApplicationTrustEnumerator GetEnumerator() { return new ApplicationTrustEnumerator(this); } /// <internalonly/> [System.Security.SecuritySafeCritical] // overrides public transparent member IEnumerator IEnumerable.GetEnumerator() { return new ApplicationTrustEnumerator(this); } /// <internalonly/> [System.Security.SecuritySafeCritical] // overrides public transparent member void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); if (array.Length - index < this.Count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); for (int i=0; i < this.Count; i++) { array.SetValue(this[i], index++); } } public void CopyTo (ApplicationTrust[] array, int index) { ((ICollection)this).CopyTo(array, index); } public bool IsSynchronized { [System.Security.SecuritySafeCritical] // overrides public transparent member get { return false; } } public object SyncRoot { [System.Security.SecuritySafeCritical] // overrides public transparent member get { return this; } } } [System.Runtime.InteropServices.ComVisible(true)] public sealed class ApplicationTrustEnumerator : IEnumerator { [System.Security.SecurityCritical] // auto-generated private ApplicationTrustCollection m_trusts; private int m_current; private ApplicationTrustEnumerator() {} [System.Security.SecurityCritical] // auto-generated internal ApplicationTrustEnumerator(ApplicationTrustCollection trusts) { m_trusts = trusts; m_current = -1; } public ApplicationTrust Current { [System.Security.SecuritySafeCritical] // auto-generated get { return m_trusts[m_current]; } } /// <internalonly/> object IEnumerator.Current { [System.Security.SecuritySafeCritical] // auto-generated get { return (object) m_trusts[m_current]; } } [System.Security.SecuritySafeCritical] // auto-generated public bool MoveNext() { if (m_current == ((int) m_trusts.Count - 1)) return false; m_current++; return true; } public void Reset() { m_current = -1; } } #endif // FEATURE_CLICKONCE }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if ODATALIB_ASYNC || ASTORIA_CLIENT #if ODATALIB namespace Microsoft.Data.OData #else namespace System.Data.Services.Client #endif { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; #if ASTORIA_CLIENT using ExceptionUtils = CommonUtil; #endif #endregion Namespaces /// <summary> /// Class with utility methods for working with and implementing Task based APIs /// </summary> internal static class TaskUtils { #region Completed task /// <summary> /// Already completed task. /// </summary> private static Task completedTask; /// <summary> /// Returns already completed task instance. /// </summary> internal static Task CompletedTask { get { DebugUtils.CheckNoExternalCallers(); // Note that in case of two threads competing here we would create two completed tasks, but only one // will be stored in the static variable. In any case, they are identical for all other purposes, // so it doesn't matter which one wins if (completedTask == null) { // Create a TaskCompletionSource - since there's no non-generic version use a dummy one // and then cast to the non-generic version. TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(); taskCompletionSource.SetResult(null); completedTask = taskCompletionSource.Task; } return completedTask; } } /// <summary> /// Returns an already completed task instance with the specified result. /// </summary> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="value">The value of the result.</param> /// <returns>An already completed task with the specified result.</returns> internal static Task<T> GetCompletedTask<T>(T value) { DebugUtils.CheckNoExternalCallers(); TaskCompletionSource<T> taskCompletionSource = new TaskCompletionSource<T>(); taskCompletionSource.SetResult(value); return taskCompletionSource.Task; } #endregion #region Faulted task /// <summary> /// Returns an already completed task instance with the specified error. /// </summary> /// <param name="exception">The exception of the faulted result.</param> /// <returns>An already completed task with the specified exception.</returns> internal static Task GetFaultedTask(Exception exception) { DebugUtils.CheckNoExternalCallers(); // Since there's no non-generic version use a dummy object return value and cast to non-generic version. return GetFaultedTask<object>(exception); } /// <summary> /// Returns an already completed task instance with the specified error. /// </summary> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="exception">The exception of the faulted result.</param> /// <returns>An already completed task with the specified exception.</returns> internal static Task<T> GetFaultedTask<T>(Exception exception) { DebugUtils.CheckNoExternalCallers(); TaskCompletionSource<T> taskCompletionSource = new TaskCompletionSource<T>(); taskCompletionSource.SetException(exception); return taskCompletionSource.Task; } #endregion #region GetTaskForSynchronousOperation /// <summary> /// Returns an already completed task for the specified synchronous operation. /// </summary> /// <param name="synchronousOperation">The synchronous operation to perform.</param> /// <returns>An already completed task. If the <paramref name="synchronousOperation"/> succeeded this will be a successfully completed task, /// otherwise it will be a faulted task holding the exception thrown.</returns> /// <remarks>The advantage of this method over CompletedTask property is that if the <paramref name="synchronousOperation"/> fails /// this method returns a faulted task, instead of throwing exception.</remarks> internal static Task GetTaskForSynchronousOperation(Action synchronousOperation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(synchronousOperation != null, "synchronousOperation != null"); try { synchronousOperation(); return TaskUtils.CompletedTask; } catch (Exception e) { if (!ExceptionUtils.IsCatchableExceptionType(e)) { throw; } return TaskUtils.GetFaultedTask(e); } } /// <summary> /// Returns an already completed task for the specified synchronous operation. /// </summary> /// <typeparam name="T">The type of the result returned by the operation. This MUST NOT be a Task type.</typeparam> /// <param name="synchronousOperation">The synchronous operation to perform.</param> /// <returns>An already completed task. If the <paramref name="synchronousOperation"/> succeeded this will be a successfully completed task, /// otherwise it will be a faulted task holding the exception thrown.</returns> /// <remarks>The advantage of this method over GetCompletedTask property is that if the <paramref name="synchronousOperation"/> fails /// this method returns a faulted task, instead of throwing exception.</remarks> internal static Task<T> GetTaskForSynchronousOperation<T>(Func<T> synchronousOperation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(synchronousOperation != null, "synchronousOperation != null"); Debug.Assert(!(typeof(Task).IsAssignableFrom(typeof(T))), "This method doesn't support operations returning Task instances."); try { T result = synchronousOperation(); return TaskUtils.GetCompletedTask<T>(result); } catch (Exception e) { if (!ExceptionUtils.IsCatchableExceptionType(e)) { throw; } return TaskUtils.GetFaultedTask<T>(e); } } /// <summary> /// Returns an already completed task for the specified synchronous operation which returns a task. /// </summary> /// <param name="synchronousOperation">The synchronous operation to perform.</param> /// <returns>The task returned by the <paramref name="synchronousOperation"/> or a faulted task if the operation failed.</returns> /// <remarks>The advantage of this method over direct call is that if the <paramref name="synchronousOperation"/> fails /// this method returns a faulted task, instead of throwing exception.</remarks> internal static Task GetTaskForSynchronousOperationReturningTask(Func<Task> synchronousOperation) { DebugUtils.CheckNoExternalCallers(); try { return synchronousOperation(); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } return TaskUtils.GetFaultedTask(exception); } } #endregion #region FollowOnSuccessWith /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks>This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures.</remarks> internal static Task FollowOnSuccessWith(this Task antecedentTask, Action<Task> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnSuccessWithImplementation<object>(antecedentTask, t => { operation(t); return null; }); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <typeparam name="TFollowupTaskResult">The result type of the operation. This MUST NOT be a Task or a type derived from Task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// This method doesn't support operations which return another Task instance, to use that call FollowOnSuccessWithTask instead. /// </remarks> internal static Task<TFollowupTaskResult> FollowOnSuccessWith<TFollowupTaskResult>(this Task antecedentTask, Func<Task, TFollowupTaskResult> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnSuccessWithImplementation(antecedentTask, operation); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <typeparam name="TAntecedentTaskResult">The result type of the antecedent task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks>This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures.</remarks> internal static Task FollowOnSuccessWith<TAntecedentTaskResult>(this Task<TAntecedentTaskResult> antecedentTask, Action<Task<TAntecedentTaskResult>> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnSuccessWithImplementation<object>(antecedentTask, t => { operation((Task<TAntecedentTaskResult>)t); return null; }); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <typeparam name="TAntecedentTaskResult">The result type of the antecedent task.</typeparam> /// <typeparam name="TFollowupTaskResult">The result type of the operation. This MUST NOT be a Task or a type derived from Task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// This method doesn't support operations which return another Task instance, to use that call FollowOnSuccessWithTask instead. /// </remarks> internal static Task<TFollowupTaskResult> FollowOnSuccessWith<TAntecedentTaskResult, TFollowupTaskResult>(this Task<TAntecedentTaskResult> antecedentTask, Func<Task<TAntecedentTaskResult>, TFollowupTaskResult> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnSuccessWithImplementation(antecedentTask, t => operation((Task<TAntecedentTaskResult>)t)); } #endregion #region FollowOnSuccessWithTask /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// This method handles operation which returns another task. The method will unwrap and return a task which finishes when both /// the antecedent task, the operation as well as the task returned by that operation finished. /// </remarks> internal static Task FollowOnSuccessWithTask(this Task antecedentTask, Func<Task, Task> operation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); TaskCompletionSource<Task> taskCompletionSource = new TaskCompletionSource<Task>(); antecedentTask.ContinueWith( (taskToContinueOn) => FollowOnSuccessWithContinuation(taskToContinueOn, taskCompletionSource, operation), TaskContinuationOptions.ExecuteSynchronously); return taskCompletionSource.Task.Unwrap(); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <typeparam name="TAntecedentTaskResult">The result type of the antecedent task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// This method handles operation which returns another task. The method will unwrap and return a task which finishes when both /// the antecedent task, the operation as well as the task returned by that operation finished. /// </remarks> internal static Task FollowOnSuccessWithTask<TAntecedentTaskResult>(this Task<TAntecedentTaskResult> antecedentTask, Func<Task<TAntecedentTaskResult>, Task> operation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); TaskCompletionSource<Task> taskCompletionSource = new TaskCompletionSource<Task>(); antecedentTask.ContinueWith( (taskToContinueOn) => FollowOnSuccessWithContinuation(taskToContinueOn, taskCompletionSource, (taskForOperation) => operation((Task<TAntecedentTaskResult>)taskForOperation)), TaskContinuationOptions.ExecuteSynchronously); return taskCompletionSource.Task.Unwrap(); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task succeeded. /// </summary> /// <typeparam name="TAntecedentTaskResult">The result type of the antecedent task.</typeparam> /// <typeparam name="TFollowupTaskResult">The result type of the operation. This MUST NOT be a Task or a type derived from Task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> succeeded.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// This method handles operation which returns another task. The method will unwrap and return a task which finishes when both /// the antecedent task, the operation as well as the task returned by that operation finished. /// </remarks> internal static Task<TFollowupTaskResult> FollowOnSuccessWithTask<TAntecedentTaskResult, TFollowupTaskResult>(this Task<TAntecedentTaskResult> antecedentTask, Func<Task<TAntecedentTaskResult>, Task<TFollowupTaskResult>> operation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); TaskCompletionSource<Task<TFollowupTaskResult>> taskCompletionSource = new TaskCompletionSource<Task<TFollowupTaskResult>>(); antecedentTask.ContinueWith( (taskToContinueOn) => FollowOnSuccessWithContinuation(taskToContinueOn, taskCompletionSource, (taskForOperation) => operation((Task<TAntecedentTaskResult>)taskForOperation)), TaskContinuationOptions.ExecuteSynchronously); return taskCompletionSource.Task.Unwrap(); } #endregion #region FollowOnFaultWith /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task faulted. /// </summary> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> faulted.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks>This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures.</remarks> internal static Task FollowOnFaultWith(this Task antecedentTask, Action<Task> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnFaultWithImplementation<object>(antecedentTask, t => null, operation); } /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will only be invoked if the antecendent task faulted. /// </summary> /// <typeparam name="TResult">The type of the result of the task.</typeparam> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute if the <paramref name="antecedentTask"/> faulted.</param> /// <returns>A new task which represents the antecedent task followed by a conditional invoke to the operation.</returns> /// <remarks>This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures.</remarks> internal static Task<TResult> FollowOnFaultWith<TResult>(this Task<TResult> antecedentTask, Action<Task<TResult>> operation) { DebugUtils.CheckNoExternalCallers(); return FollowOnFaultWithImplementation(antecedentTask, t => ((Task<TResult>)t).Result, t => operation((Task<TResult>)t)); } #endregion #region FollowAlwaysWith /// <summary> /// Returns a new task which will consist of the <paramref name="antecedentTask"/> followed by a call to the <paramref name="operation"/> /// which will get called no matter what the result of the antecedent task was. /// </summary> /// <param name="antecedentTask">The task to "append" the operation to.</param> /// <param name="operation">The operation to execute after the <paramref name="antecedentTask"/> finished.</param> /// <returns>A new task which represents the antecedent task followed by an invoke to the operation.</returns> /// <remarks> /// This method unlike ContinueWith will return a task which will fail if the antecedent task fails, thus it propagates failures. /// Note that the operation may not return any value, since the original result of the antecedent task will be used always. /// Also if the operation fails, the resulting task fails. If both tasks fail, the antecedent task failure is reported only.</remarks> internal static Task FollowAlwaysWith(this Task antecedentTask, Action<Task> operation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(); antecedentTask.ContinueWith( t => { Exception operationException = null; try { operation(t); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } operationException = exception; } switch (t.Status) { case TaskStatus.RanToCompletion: if (operationException != null) { taskCompletionSource.TrySetException(operationException); } else { taskCompletionSource.TrySetResult(null); } break; case TaskStatus.Faulted: // If the parent task failed, use that exception instead of the follow up operation's exception (if there was one). taskCompletionSource.TrySetException(t.Exception); break; case TaskStatus.Canceled: if (operationException != null) { taskCompletionSource.TrySetException(operationException); } else { taskCompletionSource.TrySetCanceled(); } break; } }, TaskContinuationOptions.ExecuteSynchronously) // This is only for the body of delegate in the .ContinueWith, the antecedent task failures are handles by the body itself. .IgnoreExceptions(); return taskCompletionSource.Task; } #endregion #region Task.IgnoreExceptions - copied from Samples for Parallel Programming /// <summary>Suppresses default exception handling of a Task that would otherwise reraise the exception on the finalizer thread.</summary> /// <param name="task">The Task to be monitored.</param> /// <returns>The original Task.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", Justification = "Need to access t.Exception to invoke the getter which will mark the Task to not throw the exception.")] internal static Task IgnoreExceptions(this Task task) { DebugUtils.CheckNoExternalCallers(); task.ContinueWith( t => { var ignored = t.Exception; }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); return task; } #endregion Task.IgnoreExceptions - copied from Samples for Parallel Programming #region TaskFactory.GetTargetScheduler - copied from Samples for Parallel Programming /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary> /// <param name="factory">Factory to get the scheduler for.</param> /// <returns>The scheduler for the specified factory.</returns> internal static TaskScheduler GetTargetScheduler(this TaskFactory factory) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(factory != null, "factory != null"); return factory.Scheduler ?? TaskScheduler.Current; } #endregion TaskFactory.GetTargetScheduler - copied from Samples for Parallel Programming #region TaskFactory.Iterate - copied from Samples for Parallel Programming //// Note that if we would migrate to .NET 4.5 and could get dependency on the "await" keyword, all of this is not needed //// and we could use the await functionality instead. /// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <returns>A Task that represents the complete asynchronous operation.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Stores the exception so that it doesn't bring down the process but isntead rethrows on the task calling thread.")] internal static Task Iterate( this TaskFactory factory, IEnumerable<Task> source) { DebugUtils.CheckNoExternalCallers(); // Validate/update parameters Debug.Assert(factory != null, "factory != null"); Debug.Assert(source != null, "source != null"); // Get an enumerator from the enumerable var enumerator = source.GetEnumerator(); Debug.Assert(enumerator != null, "enumerator != null"); // Create the task to be returned to the caller. And ensure // that when everything is done, the enumerator is cleaned up. var trc = new TaskCompletionSource<object>(null, factory.CreationOptions); trc.Task.ContinueWith(_ => enumerator.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // This will be called every time more work can be done. Action<Task> recursiveBody = null; recursiveBody = antecedent => { try { // If the previous task completed with any exceptions, bail if (antecedent != null && antecedent.IsFaulted) { trc.TrySetException(antecedent.Exception); return; } // If we should continue iterating and there's more to iterate // over, create a continuation to continue processing. We only // want to continue processing once the current Task (as yielded // from the enumerator) is complete. if (enumerator.MoveNext()) { var nextTask = enumerator.Current; // The IgnoreException here is effective only for the recursiveBody code // (not the nextTask, which is being checked by the recursiveBody above). // And since the recursiveBody already catches all exceptions except for the uncatchable // ones, we think it's OK to ignore all those exception in the finalizer thread. nextTask.ContinueWith(recursiveBody).IgnoreExceptions(); } else { // Otherwise, we're done trc.TrySetResult(null); } } catch (Exception exc) { if (!ExceptionUtils.IsCatchableExceptionType(exc)) { throw; } // If MoveNext throws an exception, propagate that to the user, // either as cancellation or as a fault var oce = exc as OperationCanceledException; if (oce != null && oce.CancellationToken == factory.CancellationToken) { trc.TrySetCanceled(); } else { trc.TrySetException(exc); } } }; // Get things started by launching the first task // The IgnoreException here is effective only for the recursiveBody code // (not the nextTask, which is being checked by the recursiveBody above). // And since the recursiveBody already catches all exceptions except for the uncatchable // ones, we think it's OK to ignore all those exception in the finalizer thread. factory.StartNew(() => recursiveBody(null), CancellationToken.None, TaskCreationOptions.None, factory.GetTargetScheduler()).IgnoreExceptions(); // Return the representative task to the user return trc.Task; } #endregion TaskFactory.Iterate - copied from Samples for Parallel Programming #region FollowOnSuccess helpers /// <summary> /// The func used as the continuation (the func in the ContinueWith) for FollowOnSuccess implementations. /// </summary> /// <typeparam name="TResult">The type of the result of the operation to follow up with.</typeparam> /// <param name="antecedentTask">The task which just finished.</param> /// <param name="taskCompletionSource">The task completion source to apply the result to.</param> /// <param name="operation">The func to execute as the follow up action in case of success of the <paramref name="antecedentTask"/>.</param> private static void FollowOnSuccessWithContinuation<TResult>(Task antecedentTask, TaskCompletionSource<TResult> taskCompletionSource, Func<Task, TResult> operation) { switch (antecedentTask.Status) { case TaskStatus.RanToCompletion: try { taskCompletionSource.TrySetResult(operation(antecedentTask)); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } taskCompletionSource.TrySetException(exception); } break; case TaskStatus.Faulted: taskCompletionSource.TrySetException(antecedentTask.Exception); break; case TaskStatus.Canceled: taskCompletionSource.TrySetCanceled(); break; } } /// <summary> /// The implementation helper for FollowOnSuccess methods which don't allow result type of Task. /// </summary> /// <typeparam name="TResult">The type of the result of the followup operation, this MUST NOT be a Task type.</typeparam> /// <param name="antecedentTask">The task to follow with operation.</param> /// <param name="operation">The operation to follow up with.</param> /// <returns>A new Task which wraps both the <paramref name="antecedentTask"/> and the conditional execution of <paramref name="operation"/>.</returns> private static Task<TResult> FollowOnSuccessWithImplementation<TResult>(Task antecedentTask, Func<Task, TResult> operation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); Debug.Assert( !(typeof(Task).IsAssignableFrom(typeof(TResult))), "It's not valid to call FollowOnSucessWith on an operation which returns a Task, instead use FollowOnSuccessWithTask."); TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>(); antecedentTask.ContinueWith( (taskToContinueOn) => FollowOnSuccessWithContinuation(taskToContinueOn, taskCompletionSource, operation), TaskContinuationOptions.ExecuteSynchronously) // This is only for the body of delegate in the .ContinueWith, the antecedent task failures are handles by the body itself. .IgnoreExceptions(); return taskCompletionSource.Task; } #endregion #region FollowOnFault helpers /// <summary> /// The implementation helper for FollowOnFault methods. /// </summary> /// <typeparam name="TResult">The type of the result of the task.</typeparam> /// <param name="antecedentTask">The task to follow with operation in case of fault.</param> /// <param name="getTaskResult">Func which gets a task result value.</param> /// <param name="operation">The operation to follow up with.</param> /// <returns>A new Task which wraps both the <paramref name="antecedentTask"/> and the conditional execution of <paramref name="operation"/>.</returns> private static Task<TResult> FollowOnFaultWithImplementation<TResult>(Task antecedentTask, Func<Task, TResult> getTaskResult, Action<Task> operation) { Debug.Assert(antecedentTask != null, "antecedentTask != null"); Debug.Assert(operation != null, "operation != null"); TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>(); antecedentTask.ContinueWith( t => { switch (t.Status) { case TaskStatus.RanToCompletion: taskCompletionSource.TrySetResult(getTaskResult(t)); break; case TaskStatus.Faulted: try { operation(t); taskCompletionSource.TrySetException(t.Exception); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } AggregateException aggregateException = new AggregateException(t.Exception, exception); taskCompletionSource.TrySetException(aggregateException); } break; case TaskStatus.Canceled: taskCompletionSource.TrySetCanceled(); break; } }, TaskContinuationOptions.ExecuteSynchronously) // This is only for the body of delegate in the .ContinueWith, the antecedent task failures are handles by the body itself. .IgnoreExceptions(); return taskCompletionSource.Task; } #endregion } } #endif
/* ==================================================================== 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 NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using NPOI.XSSF; using NPOI.XSSF.Model; using NPOI.XSSF.UserModel; using NUnit.Framework; using System; using System.Drawing; namespace TestCases.XSSF.UserModel { /** * Tests functionality of the XSSFRichTextRun object * * @author Yegor Kozlov */ [TestFixture] public class TestXSSFRichTextString { [Test] public void TestCreate() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); Assert.AreEqual("Apache POI", rt.String); Assert.AreEqual(false, rt.HasFormatting()); CT_Rst st = rt.GetCTRst(); Assert.IsTrue(st.IsSetT()); Assert.AreEqual("Apache POI", st.t); Assert.AreEqual(false, rt.HasFormatting()); rt.Append(" is cool stuff"); Assert.AreEqual(2, st.sizeOfRArray()); Assert.IsFalse(st.IsSetT()); Assert.AreEqual("Apache POI is cool stuff", rt.String); Assert.AreEqual(false, rt.HasFormatting()); } [Test] public void TestEmpty() { XSSFRichTextString rt = new XSSFRichTextString(); Assert.AreEqual(0, rt.GetIndexOfFormattingRun(9999)); Assert.AreEqual(-1, rt.GetLengthOfFormattingRun(9999)); Assert.IsNull(rt.GetFontAtIndex(9999)); } [Test] public void TestApplyFont() { XSSFRichTextString rt = new XSSFRichTextString(); rt.Append("123"); rt.Append("4567"); rt.Append("89"); Assert.AreEqual("123456789", rt.String); Assert.AreEqual(false, rt.HasFormatting()); XSSFFont font1 = new XSSFFont(); font1.IsBold = (true); rt.ApplyFont(2, 5, font1); Assert.AreEqual(true, rt.HasFormatting()); Assert.AreEqual(4, rt.NumFormattingRuns); Assert.AreEqual(0, rt.GetIndexOfFormattingRun(0)); Assert.AreEqual("12", rt.GetCTRst().GetRArray(0).t); Assert.AreEqual(2, rt.GetIndexOfFormattingRun(1)); Assert.AreEqual("345", rt.GetCTRst().GetRArray(1).t); Assert.AreEqual(5, rt.GetIndexOfFormattingRun(2)); Assert.AreEqual(2, rt.GetLengthOfFormattingRun(2)); Assert.AreEqual("67", rt.GetCTRst().GetRArray(2).t); Assert.AreEqual(7, rt.GetIndexOfFormattingRun(3)); Assert.AreEqual(2, rt.GetLengthOfFormattingRun(3)); Assert.AreEqual("89", rt.GetCTRst().GetRArray(3).t); Assert.AreEqual(-1, rt.GetIndexOfFormattingRun(9999)); Assert.AreEqual(-1, rt.GetLengthOfFormattingRun(9999)); Assert.IsNull(rt.GetFontAtIndex(9999)); } [Test] public void TestApplyFontIndex() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); rt.ApplyFont(0, 10, (short)1); rt.ApplyFont((short)1); Assert.IsNotNull(rt.GetFontAtIndex(0)); } [Test] public void TestApplyFontWithStyles() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); StylesTable tbl = new StylesTable(); rt.SetStylesTableReference(tbl); try { rt.ApplyFont(0, 10, (short)1); Assert.Fail("Fails without styles in the table"); } catch (ArgumentOutOfRangeException e) { // expected } tbl.PutFont(new XSSFFont()); rt.ApplyFont(0, 10, (short)1); rt.ApplyFont((short)1); } [Test] public void TestApplyFontException() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); rt.ApplyFont(0, 0, (short)1); try { rt.ApplyFont(11, 10, (short)1); Assert.Fail("Should catch Exception here"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.Contains("11")); } try { rt.ApplyFont(-1, 10, (short)1); Assert.Fail("Should catch Exception here"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.Contains("-1")); } try { rt.ApplyFont(0, 555, (short)1); Assert.Fail("Should catch Exception here"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.Contains("555")); } } [Test] public void TestClearFormatting() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); Assert.AreEqual("Apache POI", rt.String); Assert.AreEqual(false, rt.HasFormatting()); rt.ClearFormatting(); CT_Rst st = rt.GetCTRst(); Assert.IsTrue(st.IsSetT()); Assert.AreEqual("Apache POI", rt.String); Assert.AreEqual(0, rt.NumFormattingRuns); Assert.AreEqual(false, rt.HasFormatting()); XSSFFont font = new XSSFFont(); font.IsBold = true; rt.ApplyFont(7, 10, font); Assert.AreEqual(2, rt.NumFormattingRuns); Assert.AreEqual(true, rt.HasFormatting()); rt.ClearFormatting(); Assert.AreEqual("Apache POI", rt.String); Assert.AreEqual(0, rt.NumFormattingRuns); Assert.AreEqual(false, rt.HasFormatting()); } [Test] public void TestGetFonts() { XSSFRichTextString rt = new XSSFRichTextString(); XSSFFont font1 = new XSSFFont(); font1.FontName = ("Arial"); font1.IsItalic = (true); rt.Append("The quick", font1); XSSFFont font1FR = (XSSFFont)rt.GetFontOfFormattingRun(0); Assert.AreEqual(font1.IsItalic, font1FR.IsItalic); Assert.AreEqual(font1.FontName, font1FR.FontName); XSSFFont font2 = new XSSFFont(); font2.FontName = ("Courier"); font2.IsBold = (true); rt.Append(" brown fox", font2); XSSFFont font2FR = (XSSFFont)rt.GetFontOfFormattingRun(1); Assert.AreEqual(font2.IsBold, font2FR.IsBold); Assert.AreEqual(font2.FontName, font2FR.FontName); } [Test] /** * make sure we insert xml:space="preserve" attribute * if a string has leading or trailing white spaces */ public void TestPreserveSpaces() { XSSFRichTextString rt = new XSSFRichTextString("Apache"); CT_Rst ct = rt.GetCTRst(); string t=ct.t; Assert.AreEqual("<t>Apache</t>", ct.XmlText); rt.String = " Apache"; Assert.AreEqual("<t xml:space=\"preserve\"> Apache</t>", ct.XmlText); rt.Append(" POI"); rt.Append(" "); Assert.AreEqual(" Apache POI ", rt.String); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> Apache</t>", rt.GetCTRst().GetRArray(0).xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> POI</xml-fragment>", rt.getCTRst().getRArray(1).xgetT().xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> </xml-fragment>", rt.getCTRst().getRArray(2).xgetT().xmlText()); } /** * Ensure that strings with the color set as RGB are treated differently when the color is different. */ [Test] public void TestRgbColor() { const string testText = "Apache"; XSSFRichTextString rt = new XSSFRichTextString(testText); XSSFFont font = new XSSFFont { FontName = "Times New Roman", FontHeightInPoints = 11 }; font.SetColor(new XSSFColor(Color.Red)); rt.ApplyFont(0, testText.Length, font); CT_Rst ct = rt.GetCTRst(); Assert.AreEqual("<r><rPr><color rgb=\"FF0000\"/><rFont val=\"Times New Roman\"/><sz val=\"11\"/></rPr><t>Apache</t></r>", ct.XmlText); } /** * Test that unicode representation_ xHHHH_ is properly Processed */ [Test] public void TestUtfDecode() { CT_Rst st = new CT_Rst(); st.t = ("abc_x000D_2ef_x000D_"); XSSFRichTextString rt = new XSSFRichTextString(st); //_x000D_ is Converted into carriage return Assert.AreEqual("abc\r2ef\r", rt.String); } [Ignore("Not Implemented")] public void TestApplyFont_lowlevel() { CT_Rst st = new CT_Rst(); String text = "Apache Software Foundation"; XSSFRichTextString str = new XSSFRichTextString(text); Assert.AreEqual(26, text.Length); st.AddNewR().t = (text); //SortedDictionary<int, CT_RPrElt> formats = str.GetFormatMap(st); //Assert.AreEqual(1, formats.Count); //Assert.AreEqual(26, (int)formats.Keys[0]); //Assert.IsNull(formats.Get(formats.firstKey())); //CT_RPrElt fmt1 = new CT_RPrElt(); //str.ApplyFont(formats, 0, 6, fmt1); //Assert.AreEqual(2, formats.Count); //Assert.AreEqual("[6, 26]", formats.Keys.ToString()); //Object[] Runs1 = formats.Values.ToArray(); //Assert.AreSame(fmt1, Runs1[0]); //Assert.AreSame(null, Runs1[1]); //CT_RPrElt fmt2 = new CT_RPrElt(); //str.ApplyFont(formats, 7, 15, fmt2); //Assert.AreEqual(4, formats.Count); //Assert.AreEqual("[6, 7, 15, 26]", formats.Keys.ToString()); //Object[] Runs2 = formats.Values.ToArray(); //Assert.AreSame(fmt1, Runs2[0]); //Assert.AreSame(null, Runs2[1]); //Assert.AreSame(fmt2, Runs2[2]); //Assert.AreSame(null, Runs2[3]); //CT_RPrElt fmt3 = new CT_RPrElt(); //str.ApplyFont(formats, 6, 7, fmt3); //Assert.AreEqual(4, formats.Count); //Assert.AreEqual("[6, 7, 15, 26]", formats.Keys.ToString()); //Object[] Runs3 = formats.Values.ToArray(); //Assert.AreSame(fmt1, Runs3[0]); //Assert.AreSame(fmt3, Runs3[1]); //Assert.AreSame(fmt2, Runs3[2]); //Assert.AreSame(null, Runs3[3]); //CT_RPrElt fmt4 = new CT_RPrElt(); //str.ApplyFont(formats, 0, 7, fmt4); //Assert.AreEqual(3, formats.Count); //Assert.AreEqual("[7, 15, 26]", formats.Keys.ToString()); //Object[] Runs4 = formats.Values.ToArray(); //Assert.AreSame(fmt4, Runs4[0]); //Assert.AreSame(fmt2, Runs4[1]); //Assert.AreSame(null, Runs4[2]); //CT_RPrElt fmt5 = new CT_RPrElt(); //str.ApplyFont(formats, 0, 26, fmt5); //Assert.AreEqual(1, formats.Count); //Assert.AreEqual("[26]", formats.Keys.ToString()); //Object[] Runs5 = formats.Values.ToArray(); //Assert.AreSame(fmt5, Runs5[0]); //CT_RPrElt fmt6 = new CT_RPrElt(); //str.ApplyFont(formats, 15, 26, fmt6); //Assert.AreEqual(2, formats.Count); //Assert.AreEqual("[15, 26]", formats.Keys.ToString()); //Object[] Runs6 = formats.Values.ToArray(); //Assert.AreSame(fmt5, Runs6[0]); //Assert.AreSame(fmt6, Runs6[1]); //str.ApplyFont(formats, 0, 26, null); //Assert.AreEqual(1, formats.Count); //Assert.AreEqual("[26]", formats.Keys.ToString()); //Object[] Runs7 = formats.Values.ToArray(); //Assert.AreSame(null, Runs7[0]); //str.ApplyFont(formats, 15, 26, fmt6); //Assert.AreEqual(2, formats.Count); //Assert.AreEqual("[15, 26]", formats.Keys.ToString()); //Object[] Runs8 = formats.Values.ToArray(); //Assert.AreSame(null, Runs8[0]); //Assert.AreSame(fmt6, Runs8[1]); //str.ApplyFont(formats, 15, 26, fmt5); //Assert.AreEqual(2, formats.Count); //Assert.AreEqual("[15, 26]", formats.Keys.ToString()); //Object[] Runs9 = formats.Values.ToArray(); //Assert.AreSame(null, Runs9[0]); //Assert.AreSame(fmt5, Runs9[1]); //str.ApplyFont(formats, 2, 20, fmt6); //Assert.AreEqual(3, formats.Count); //Assert.AreEqual("[2, 20, 26]", formats.Keys.ToString()); //Object[] Runs10 = formats.Values.ToArray(); //Assert.AreSame(null, Runs10[0]); //Assert.AreSame(fmt6, Runs10[1]); //Assert.AreSame(fmt5, Runs10[2]); //str.ApplyFont(formats, 22, 24, fmt4); //Assert.AreEqual(5, formats.Count); //Assert.AreEqual("[2, 20, 22, 24, 26]", formats.Keys.ToString()); //Object[] Runs11 = formats.Values.ToArray(); //Assert.AreSame(null, Runs11[0]); //Assert.AreSame(fmt6, Runs11[1]); //Assert.AreSame(fmt5, Runs11[2]); //Assert.AreSame(fmt4, Runs11[3]); //Assert.AreSame(fmt5, Runs11[4]); //str.ApplyFont(formats, 0, 10, fmt1); //Assert.AreEqual(5, formats.Count); //Assert.AreEqual("[10, 20, 22, 24, 26]", formats.Keys.ToString()); //Object[] Runs12 = formats.Values.ToArray(); //Assert.AreSame(fmt1, Runs12[0]); //Assert.AreSame(fmt6, Runs12[1]); //Assert.AreSame(fmt5, Runs12[2]); //Assert.AreSame(fmt4, Runs12[3]); //Assert.AreSame(fmt5, Runs12[4]); Assert.Fail("implement STXString"); } [Test] public void TestApplyFont_usermodel() { String text = "Apache Software Foundation"; XSSFRichTextString str = new XSSFRichTextString(text); XSSFFont font1 = new XSSFFont(); XSSFFont font2 = new XSSFFont(); XSSFFont font3 = new XSSFFont(); str.ApplyFont(font1); Assert.AreEqual(1, str.NumFormattingRuns); str.ApplyFont(0, 6, font1); str.ApplyFont(6, text.Length, font2); Assert.AreEqual(2, str.NumFormattingRuns); Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t); Assert.AreEqual(" Software Foundation", str.GetCTRst().GetRArray(1).t); str.ApplyFont(15, 26, font3); Assert.AreEqual(3, str.NumFormattingRuns); Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t); Assert.AreEqual(" Software", str.GetCTRst().GetRArray(1).t); Assert.AreEqual(" Foundation", str.GetCTRst().GetRArray(2).t); str.ApplyFont(6, text.Length, font2); Assert.AreEqual(2, str.NumFormattingRuns); Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t); Assert.AreEqual(" Software Foundation", str.GetCTRst().GetRArray(1).t); } [Ignore("test")] public void TestLineBreaks_bug48877() { //XSSFFont font = new XSSFFont(); //font.Boldweight = (short)FontBoldWeight.Bold; //font.FontHeightInPoints = ((short)14); //XSSFRichTextString str; //STXstring t1, t2, t3; //str = new XSSFRichTextString("Incorrect\nLine-Breaking"); //str.ApplyFont(0, 8, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //Assert.AreEqual("<xml-fragment>Incorrec</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment>t\nLine-Breaking</xml-fragment>", t2.xmlText()); //str = new XSSFRichTextString("Incorrect\nLine-Breaking"); //str.ApplyFont(0, 9, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //Assert.AreEqual("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\nLine-Breaking</xml-fragment>", t2.xmlText()); //str = new XSSFRichTextString("Incorrect\n Line-Breaking"); //str.ApplyFont(0, 9, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //Assert.AreEqual("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n Line-Breaking</xml-fragment>", t2.xmlText()); //str = new XSSFRichTextString("Tab\tSeparated\n"); //t1 = str.GetCTRst().xgetT(); //// trailing \n causes must be preserved //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">Tab\tSeparated\n</xml-fragment>", t1.xmlText()); //str.ApplyFont(0, 3, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //Assert.AreEqual("<xml-fragment>Tab</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\tSeparated\n</xml-fragment>", t2.xmlText()); //str = new XSSFRichTextString("Tab\tSeparated\n"); //str.ApplyFont(0, 4, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //// YK: don't know why, but XmlBeans Converts leading tab characters to spaces ////Assert.AreEqual("<xml-fragment>Tab\t</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">Separated\n</xml-fragment>", t2.xmlText()); //str = new XSSFRichTextString("\n\n\nNew Line\n\n"); //str.ApplyFont(0, 3, font); //str.ApplyFont(11, 13, font); //t1 = str.GetCTRst().r[0].xgetT(); //t2 = str.GetCTRst().r[1].xgetT(); //t3 = str.GetCTRst().r[2].xgetT(); //// YK: don't know why, but XmlBeans Converts leading tab characters to spaces //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n\n\n</xml-fragment>", t1.xmlText()); //Assert.AreEqual("<xml-fragment>New Line</xml-fragment>", t2.xmlText()); //Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n\n</xml-fragment>", t3.xmlText()); Assert.Fail("implement STXString"); } [Test] public void TestBug56511() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56511.xlsx"); foreach (XSSFSheet sheet in wb) { int lastRow = sheet.LastRowNum; for (int rowIdx = sheet.FirstRowNum; rowIdx <= lastRow; rowIdx++) { XSSFRow row = sheet.GetRow(rowIdx) as XSSFRow; if (row != null) { int lastCell = row.LastCellNum; for (int cellIdx = row.FirstCellNum; cellIdx <= lastCell; cellIdx++) { XSSFCell cell = row.GetCell(cellIdx) as XSSFCell; if (cell != null) { //System.out.Println("row " + rowIdx + " column " + cellIdx + ": " + cell.CellType + ": " + cell.ToString()); XSSFRichTextString richText = cell.RichStringCellValue as XSSFRichTextString; int anzFormattingRuns = richText.NumFormattingRuns; for (int run = 0; run < anzFormattingRuns; run++) { /*XSSFFont font =*/ richText.GetFontOfFormattingRun(run); //System.out.Println(" run " + run // + " font " + (font == null ? "<null>" : font.FontName)); } } } } } } } [Test] public void TestBug56511_values() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56511.xlsx"); ISheet sheet = wb.GetSheetAt(0); IRow row = sheet.GetRow(0); // verify the values to ensure future Changes keep the returned information equal XSSFRichTextString rt = (XSSFRichTextString)row.GetCell(0).RichStringCellValue; Assert.AreEqual(0, rt.NumFormattingRuns); Assert.IsNull(rt.GetFontOfFormattingRun(0)); Assert.AreEqual(-1, rt.GetLengthOfFormattingRun(0)); rt = (XSSFRichTextString)row.GetCell(1).RichStringCellValue; Assert.AreEqual(0, row.GetCell(1).RichStringCellValue.NumFormattingRuns); Assert.IsNull(rt.GetFontOfFormattingRun(1)); Assert.AreEqual(-1, rt.GetLengthOfFormattingRun(1)); rt = (XSSFRichTextString)row.GetCell(2).RichStringCellValue; Assert.AreEqual(2, rt.NumFormattingRuns); Assert.IsNotNull(rt.GetFontOfFormattingRun(0)); Assert.AreEqual(4, rt.GetLengthOfFormattingRun(0)); Assert.IsNotNull(rt.GetFontOfFormattingRun(1)); Assert.AreEqual(9, rt.GetLengthOfFormattingRun(1)); Assert.IsNull(rt.GetFontOfFormattingRun(2)); rt = (XSSFRichTextString)row.GetCell(3).RichStringCellValue; Assert.AreEqual(3, rt.NumFormattingRuns); Assert.IsNull(rt.GetFontOfFormattingRun(0)); Assert.AreEqual(1, rt.GetLengthOfFormattingRun(0)); Assert.IsNotNull(rt.GetFontOfFormattingRun(1)); Assert.AreEqual(3, rt.GetLengthOfFormattingRun(1)); Assert.IsNotNull(rt.GetFontOfFormattingRun(2)); Assert.AreEqual(9, rt.GetLengthOfFormattingRun(2)); } [Test] public void TestToString() { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); Assert.IsNotNull(rt.ToString()); // TODO: normally ToString() should never return null, should we adjust this? rt = new XSSFRichTextString(); Assert.IsNull(rt.ToString()); } [Test] public void Test59008Font() { XSSFFont font = new XSSFFont(new CT_Font()); XSSFRichTextString rts = new XSSFRichTextString(); rts.Append("This is correct "); int s1 = rts.Length; rts.Append("This is Bold Red", font); int s2 = rts.Length; rts.Append(" This uses the default font rather than the cell style font"); int s3 = rts.Length; //Assert.AreEqual("<xml-fragment/>", rts.GetFontAtIndex(s1 - 1).ToString()); Assert.AreEqual("<font></font>", rts.GetFontAtIndex(s1 - 1).ToString()); Assert.AreEqual(font, rts.GetFontAtIndex(s2 - 1)); //Assert.AreEqual("<xml-fragment/>", rts.GetFontAtIndex(s3 - 1).ToString()); Assert.AreEqual("<font></font>", rts.GetFontAtIndex(s3 - 1).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. using System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tools.RuntimeClient; using System.Runtime.InteropServices; using System.Linq; using System.Text.RegularExpressions; namespace Tracing.Tests.Common { public class Logger { public static Logger logger = new Logger(); private TextWriter _log; private Stopwatch _sw; public Logger(TextWriter log = null) { _log = log ?? Console.Out; _sw = new Stopwatch(); } public void Log(string message) { if (!_sw.IsRunning) _sw.Start(); _log.WriteLine($"{_sw.Elapsed.TotalSeconds,5:f1}s: {message}"); } } public class ExpectedEventCount { // The acceptable percent error on the expected value // represented as a floating point value in [0,1]. public float Error { get; private set; } // The expected count of events. A value of -1 indicates // that count does not matter, and we are simply testing // that the provider exists in the trace. public int Count { get; private set; } public ExpectedEventCount(int count, float error = 0.0f) { Count = count; Error = error; } public bool Validate(int actualValue) { return Count == -1 || CheckErrorBounds(actualValue); } public bool CheckErrorBounds(int actualValue) { return Math.Abs(actualValue - Count) <= (Count * Error); } public static implicit operator ExpectedEventCount(int i) { return new ExpectedEventCount(i); } public override string ToString() { return $"{Count} +- {Count * Error}"; } } // This event source is used by the test infra to // to insure that providers have finished being enabled // for the session being observed. Since the client API // returns the pipe for reading _before_ it finishes // enabling the providers to write to that session, // we need to guarantee that our providers are on before // sending events. This is a _unique_ problem I imagine // should _only_ affect scenarios like these tests // where the reading and sending of events are required // to synchronize. public sealed class SentinelEventSource : EventSource { private SentinelEventSource() {} public static SentinelEventSource Log = new SentinelEventSource(); public void SentinelEvent() { WriteEvent(1, "SentinelEvent"); } } public static class SessionConfigurationExtensions { public static SessionConfiguration InjectSentinel(this SessionConfiguration sessionConfiguration) { var newProviderList = new List<Provider>(sessionConfiguration.Providers); newProviderList.Add(new Provider("SentinelEventSource")); return new SessionConfiguration(sessionConfiguration.CircularBufferSizeInMB, sessionConfiguration.Format, newProviderList.AsReadOnly()); } } public class IpcTraceTest { // This Action is executed while the trace is being collected. private Action _eventGeneratingAction; // A dictionary of event providers to number of events. // A count of -1 indicates that you are only testing for the presence of the provider // and don't care about the number of events sent private Dictionary<string, ExpectedEventCount> _expectedEventCounts; private Dictionary<string, int> _actualEventCounts = new Dictionary<string, int>(); private int _droppedEvents = 0; private SessionConfiguration _sessionConfiguration; // A function to be called with the EventPipeEventSource _before_ // the call to `source.Process()`. The function should return another // function that will be called to check whether the optional test was validated. // Example in situ: providervalidation.cs private Func<EventPipeEventSource, Func<int>> _optionalTraceValidator; IpcTraceTest( Dictionary<string, ExpectedEventCount> expectedEventCounts, Action eventGeneratingAction, SessionConfiguration? sessionConfiguration = null, Func<EventPipeEventSource, Func<int>> optionalTraceValidator = null) { _eventGeneratingAction = eventGeneratingAction; _expectedEventCounts = expectedEventCounts; _sessionConfiguration = sessionConfiguration?.InjectSentinel() ?? new SessionConfiguration( circularBufferSizeMB: 1000, format: EventPipeSerializationFormat.NetTrace, providers: new List<Provider> { new Provider("Microsoft-Windows-DotNETRuntime"), new Provider("SentinelEventSource") }); _optionalTraceValidator = optionalTraceValidator; } private int Fail(string message = "") { Logger.logger.Log("Test FAILED!"); Logger.logger.Log(message); Logger.logger.Log("Configuration:"); Logger.logger.Log("{"); Logger.logger.Log($"\tbufferSize: {_sessionConfiguration.CircularBufferSizeInMB},"); Logger.logger.Log("\tproviders: ["); foreach (var provider in _sessionConfiguration.Providers) { Logger.logger.Log($"\t\t{provider.ToString()},"); } Logger.logger.Log("\t]"); Logger.logger.Log("}\n"); Logger.logger.Log("Expected:"); Logger.logger.Log("{"); foreach (var (k, v) in _expectedEventCounts) { Logger.logger.Log($"\t\"{k}\" = {v}"); } Logger.logger.Log("}\n"); Logger.logger.Log("Actual:"); Logger.logger.Log("{"); foreach (var (k, v) in _actualEventCounts) { Logger.logger.Log($"\t\"{k}\" = {v}"); } Logger.logger.Log("}"); return -1; } private int Validate() { var isClean = EnsureCleanEnvironment(); if (!isClean) return -1; var processId = Process.GetCurrentProcess().Id; Logger.logger.Log("Connecting to EventPipe..."); var binaryReader = EventPipeClient.CollectTracing(processId, _sessionConfiguration, out var eventpipeSessionId); if (eventpipeSessionId == 0) { Logger.logger.Log("Failed to connect to EventPipe!"); return -1; } Logger.logger.Log($"Connected to EventPipe with sessionID '0x{eventpipeSessionId:x}'"); // CollectTracing returns before EventPipe::Enable has returned, so the // the sources we want to listen for may not have been enabled yet. // We'll use this sentinel EventSource to check if Enable has finished ManualResetEvent sentinelEventReceived = new ManualResetEvent(false); var sentinelTask = new Task(() => { Logger.logger.Log("Started sending sentinel events..."); while (!sentinelEventReceived.WaitOne(50)) { SentinelEventSource.Log.SentinelEvent(); } Logger.logger.Log("Stopped sending sentinel events"); }); sentinelTask.Start(); EventPipeEventSource source = null; Func<int> optionalTraceValidationCallback = null; var readerTask = new Task(() => { Logger.logger.Log("Creating EventPipeEventSource..."); source = new EventPipeEventSource(binaryReader); Logger.logger.Log("EventPipeEventSource created"); source.Dynamic.All += (eventData) => { try { if (eventData.ProviderName == "SentinelEventSource") { if (!sentinelEventReceived.WaitOne(0)) Logger.logger.Log("Saw sentinel event"); sentinelEventReceived.Set(); } else if (_actualEventCounts.TryGetValue(eventData.ProviderName, out _)) { _actualEventCounts[eventData.ProviderName]++; } else { Logger.logger.Log($"Saw new provider '{eventData.ProviderName}'"); _actualEventCounts[eventData.ProviderName] = 1; } } catch (Exception e) { Logger.logger.Log("Exception in Dynamic.All callback " + e.ToString()); } }; Logger.logger.Log("Dynamic.All callback registered"); if (_optionalTraceValidator != null) { Logger.logger.Log("Running optional trace validator"); optionalTraceValidationCallback = _optionalTraceValidator(source); Logger.logger.Log("Finished running optional trace validator"); } Logger.logger.Log("Starting stream processing..."); source.Process(); Logger.logger.Log("Stopping stream processing"); Logger.logger.Log($"Dropped {source.EventsLost} events"); }); readerTask.Start(); sentinelEventReceived.WaitOne(); Logger.logger.Log("Starting event generating action..."); _eventGeneratingAction(); Logger.logger.Log("Stopping event generating action"); Logger.logger.Log("Sending StopTracing command..."); EventPipeClient.StopTracing(processId, eventpipeSessionId); Logger.logger.Log("Finished StopTracing command"); readerTask.Wait(); Logger.logger.Log("Reader task finished"); foreach (var (provider, expectedCount) in _expectedEventCounts) { if (_actualEventCounts.TryGetValue(provider, out var actualCount)) { if (!expectedCount.Validate(actualCount)) { return Fail($"Event count mismatch for provider \"{provider}\": expected {expectedCount}, but saw {actualCount}"); } } else { return Fail($"No events for provider \"{provider}\""); } } if (optionalTraceValidationCallback != null) { Logger.logger.Log("Validating optional callback..."); return optionalTraceValidationCallback(); } else { return 100; } } // Ensure that we have a clean environment for running the test. // Specifically check that we don't have more than one match for // Diagnostic IPC sockets in the TempPath. These can be left behind // by bugs, catastrophic test failures, etc. from previous testing. // The tmp directory is only cleared on reboot, so it is possible to // run into these zombie pipes if there are failures over time. // Note: Windows has some guarantees about named pipes not living longer // the process that created them, so we don't need to check on that platform. private bool EnsureCleanEnvironment() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Logger.logger.Log("Validating clean environment..."); // mimic the RuntimeClient's code for finding OS Transports IEnumerable<FileInfo> ipcPorts = Directory.GetFiles(Path.GetTempPath()) .Select(namedPipe => new FileInfo(namedPipe)) .Where(input => Regex.IsMatch(input.Name, $"^dotnet-diagnostic-{System.Diagnostics.Process.GetCurrentProcess().Id}-(\\d+)-socket$")); if (ipcPorts.Count() > 1) { Logger.logger.Log($"Found {ipcPorts.Count()} OS transports for pid {System.Diagnostics.Process.GetCurrentProcess().Id}:"); foreach (var match in ipcPorts) { Logger.logger.Log($"\t{match.Name}"); } // Get everything _except_ the newest pipe var duplicates = ipcPorts.OrderBy(fileInfo => fileInfo.CreationTime.Ticks).SkipLast(1); foreach (var duplicate in duplicates) { Logger.logger.Log($"Attempting to delete the oldest pipe: {duplicate.FullName}"); duplicate.Delete(); // should throw if we can't delete and be caught in Validate Logger.logger.Log($"Deleted"); } var afterIpcPorts = Directory.GetFiles(Path.GetTempPath()) .Select(namedPipe => new FileInfo(namedPipe)) .Where(input => Regex.IsMatch(input.Name, $"^dotnet-diagnostic-{System.Diagnostics.Process.GetCurrentProcess().Id}-(\\d+)-socket$")); if (afterIpcPorts.Count() == 1) { return true; } else { Logger.logger.Log($"Unable to clean the environment. The following transports are on the system:"); foreach(var transport in afterIpcPorts) { Logger.logger.Log($"\t{transport.FullName}"); } return false; } } Logger.logger.Log("Environment was clean."); return true; } return true; } public static int RunAndValidateEventCounts( Dictionary<string, ExpectedEventCount> expectedEventCounts, Action eventGeneratingAction, SessionConfiguration? sessionConfiguration = null, Func<EventPipeEventSource, Func<int>> optionalTraceValidator = null) { Logger.logger.Log("==TEST STARTING=="); var test = new IpcTraceTest(expectedEventCounts, eventGeneratingAction, sessionConfiguration, optionalTraceValidator); try { var ret = test.Validate(); if (ret == 100) Logger.logger.Log("==TEST FINISHED: PASSED!=="); else Logger.logger.Log("==TEST FINISHED: FAILED!=="); return ret; } catch (Exception e) { Logger.logger.Log(e.ToString()); Logger.logger.Log("==TEST FINISHED: FAILED!=="); return -1; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using Windows.Devices.Bluetooth; using Windows.Devices.Enumeration; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { // This scenario uses a DeviceWatcher to enumerate nearby Bluetooth Low Energy devices, // displays them in a ListView, and lets the user select a device and pair it. // This device will be used by future scenarios. // For more information about device discovery and pairing, including examples of // customizing the pairing process, see the DeviceEnumerationAndPairing sample. public sealed partial class Scenario1_Discovery : Page { private MainPage rootPage = MainPage.Current; private ObservableCollection<BluetoothLEDeviceDisplay> KnownDevices = new ObservableCollection<BluetoothLEDeviceDisplay>(); private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>(); private DeviceWatcher deviceWatcher; #region UI Code public Scenario1_Discovery() { InitializeComponent(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { StopBleDeviceWatcher(); // Save the selected device's ID for use in other scenarios. var bleDeviceDisplay = ResultsListView.SelectedItem as BluetoothLEDeviceDisplay; if (bleDeviceDisplay != null) { rootPage.SelectedBleDeviceId = bleDeviceDisplay.Id; rootPage.SelectedBleDeviceName = bleDeviceDisplay.Name; } } private void EnumerateButton_Click() { if (deviceWatcher == null) { StartBleDeviceWatcher(); EnumerateButton.Content = "Stop enumerating"; rootPage.NotifyUser($"Device watcher started.", NotifyType.StatusMessage); } else { StopBleDeviceWatcher(); EnumerateButton.Content = "Start enumerating"; rootPage.NotifyUser($"Device watcher stopped.", NotifyType.StatusMessage); } } private bool Not(bool value) => !value; #endregion #region Device discovery /// <summary> /// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired). /// Attaches event handlers to populate the device collection. /// </summary> private void StartBleDeviceWatcher() { // Additional properties we would like about the device. // Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" }; // BT_Code: Example showing paired and non-paired in a single query. string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")"; deviceWatcher = DeviceInformation.CreateWatcher( aqsAllBluetoothLEDevices, requestedProperties, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. deviceWatcher.Added += DeviceWatcher_Added; deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.Removed += DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped += DeviceWatcher_Stopped; // Start over with an empty collection. KnownDevices.Clear(); // Start the watcher. Active enumeration is limited to approximately 30 seconds. // This limits power usage and reduces interference with other Bluetooth activities. // To monitor for the presence of Bluetooth LE devices for an extended period, // use the BluetoothLEAdvertisementWatcher runtime class. See the BluetoothAdvertisement // sample for an example. deviceWatcher.Start(); } /// <summary> /// Stops watching for all nearby Bluetooth devices. /// </summary> private void StopBleDeviceWatcher() { if (deviceWatcher != null) { // Unregister the event handlers. deviceWatcher.Added -= DeviceWatcher_Added; deviceWatcher.Updated -= DeviceWatcher_Updated; deviceWatcher.Removed -= DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped -= DeviceWatcher_Stopped; // Stop the watcher. deviceWatcher.Stop(); deviceWatcher = null; } } private BluetoothLEDeviceDisplay FindBluetoothLEDeviceDisplay(string id) { foreach (BluetoothLEDeviceDisplay bleDeviceDisplay in KnownDevices) { if (bleDeviceDisplay.Id == id) { return bleDeviceDisplay; } } return null; } private DeviceInformation FindUnknownDevices(string id) { foreach (DeviceInformation bleDeviceInfo in UnknownDevices) { if (bleDeviceInfo.Id == id) { return bleDeviceInfo; } } return null; } private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) { // We must update the collection on the UI thread because the collection is databound to a UI element. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (this) { Debug.WriteLine(String.Format("Added {0}{1}", deviceInfo.Id, deviceInfo.Name)); // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { // Make sure device isn't already present in the list. if (FindBluetoothLEDeviceDisplay(deviceInfo.Id) == null) { if (deviceInfo.Name != string.Empty) { // If device has a friendly name display it immediately. KnownDevices.Add(new BluetoothLEDeviceDisplay(deviceInfo)); } else { // Add it to a list in case the name gets updated later. UnknownDevices.Add(deviceInfo); } } } } }); } private async void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) { // We must update the collection on the UI thread because the collection is databound to a UI element. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (this) { Debug.WriteLine(String.Format("Updated {0}{1}", deviceInfoUpdate.Id, "")); // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { BluetoothLEDeviceDisplay bleDeviceDisplay = FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id); if (bleDeviceDisplay != null) { // Device is already being displayed - update UX. bleDeviceDisplay.Update(deviceInfoUpdate); return; } DeviceInformation deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id); if (deviceInfo != null) { deviceInfo.Update(deviceInfoUpdate); // If device has been updated with a friendly name it's no longer unknown. if (deviceInfo.Name != String.Empty) { KnownDevices.Add(new BluetoothLEDeviceDisplay(deviceInfo)); UnknownDevices.Remove(deviceInfo); } } } } }); } private async void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) { // We must update the collection on the UI thread because the collection is databound to a UI element. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (this) { Debug.WriteLine(String.Format("Removed {0}{1}", deviceInfoUpdate.Id,"")); // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { // Find the corresponding DeviceInformation in the collection and remove it. BluetoothLEDeviceDisplay bleDeviceDisplay = FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id); if (bleDeviceDisplay != null) { KnownDevices.Remove(bleDeviceDisplay); } DeviceInformation deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id); if (deviceInfo != null) { UnknownDevices.Remove(deviceInfo); } } } }); } private async void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object e) { // We must update the collection on the UI thread because the collection is databound to a UI element. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { rootPage.NotifyUser($"{KnownDevices.Count} devices found. Enumeration completed.", NotifyType.StatusMessage); } }); } private async void DeviceWatcher_Stopped(DeviceWatcher sender, object e) { // We must update the collection on the UI thread because the collection is databound to a UI element. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { rootPage.NotifyUser($"No longer watching for devices.", sender.Status == DeviceWatcherStatus.Aborted ? NotifyType.ErrorMessage : NotifyType.StatusMessage); } }); } #endregion #region Pairing private bool isBusy = false; private async void PairButton_Click() { // Do not allow a new Pair operation to start if an existing one is in progress. if (isBusy) { return; } isBusy = true; rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage); // For more information about device pairing, including examples of // customizing the pairing process, see the DeviceEnumerationAndPairing sample. // Capture the current selected item in case the user changes it while we are pairing. var bleDeviceDisplay = ResultsListView.SelectedItem as BluetoothLEDeviceDisplay; // BT_Code: Pair the currently selected device. DevicePairingResult result = await bleDeviceDisplay.DeviceInformation.Pairing.PairAsync(); rootPage.NotifyUser($"Pairing result = {result.Status}", result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); isBusy = false; } #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. namespace System.ServiceModel.Syndication { using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; public class SyndicationElementExtension { private XmlBuffer _buffer; private int _bufferElementIndex; // extensionData and extensionDataWriter are only present on the send side private object _extensionData; private ExtensionDataWriter _extensionDataWriter; private string _outerName; private string _outerNamespace; public SyndicationElementExtension(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SyndicationFeedFormatter.MoveToStartElement(reader); _outerName = reader.LocalName; _outerNamespace = reader.NamespaceURI; _buffer = new XmlBuffer(int.MaxValue); using (XmlDictionaryWriter writer = _buffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); writer.WriteNode(reader, false); writer.WriteEndElement(); } _buffer.CloseSection(); _buffer.Close(); _bufferElementIndex = 0; } public SyndicationElementExtension(object dataContractExtension) : this(dataContractExtension, (XmlObjectSerializer)null) { } public SyndicationElementExtension(object dataContractExtension, XmlObjectSerializer dataContractSerializer) : this(null, null, dataContractExtension, dataContractSerializer) { } public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension) : this(outerName, outerNamespace, dataContractExtension, null) { } public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { if (dataContractExtension == null) { throw new ArgumentNullException(nameof(dataContractExtension)); } if (outerName == string.Empty) { throw new ArgumentNullException(SR.OuterNameOfElementExtensionEmpty); } if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } _outerName = outerName; _outerNamespace = outerNamespace; _extensionData = dataContractExtension; _extensionDataWriter = new ExtensionDataWriter(_extensionData, dataContractSerializer, _outerName, _outerNamespace); } public SyndicationElementExtension(object xmlSerializerExtension, XmlSerializer serializer) { if (xmlSerializerExtension == null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } _extensionData = xmlSerializerExtension; _extensionDataWriter = new ExtensionDataWriter(_extensionData, serializer); } internal SyndicationElementExtension(XmlBuffer buffer, int bufferElementIndex, string outerName, string outerNamespace) { _buffer = buffer; _bufferElementIndex = bufferElementIndex; _outerName = outerName; _outerNamespace = outerNamespace; } public string OuterName { get { if (_outerName == null) { EnsureOuterNameAndNs(); } return _outerName; } } public string OuterNamespace { get { if (_outerName == null) { EnsureOuterNameAndNs(); } return _outerNamespace; } } public Task<TExtension> GetObject<TExtension>() { return GetObject<TExtension>(new DataContractSerializer(typeof(TExtension))); } public async Task<TExtension> GetObject<TExtension>(XmlObjectSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; } using (XmlReader reader = await GetReaderAsync()) { return (TExtension)serializer.ReadObject(reader, false); } } public async Task<TExtension> GetObject<TExtension>(XmlSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; } using (XmlReader reader = await GetReaderAsync()) { return (TExtension)serializer.Deserialize(reader); } } public async Task<XmlReader> GetReaderAsync() { await this.EnsureBuffer(); XmlReaderWrapper reader = XmlReaderWrapper.CreateFromReader(_buffer.GetReader(0)); int index = 0; reader.ReadStartElement(Rss20Constants.ExtensionWrapperTag); while (reader.IsStartElement()) { if (index == _bufferElementIndex) { break; } ++index; await reader.SkipAsync(); } return reader; } //public Task<XmlReader> GetReader() //{ // return GetReaderAsync(); //} public async Task WriteToAsync(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (_extensionDataWriter != null) { _extensionDataWriter.WriteToAsync(writer); } else { writer = XmlWriterWrapper.CreateFromWriter(writer); using (XmlReader reader = await GetReaderAsync()) { await writer.WriteNodeAsync(reader, false); } } } private async Task EnsureBuffer() { if (_buffer == null) { _buffer = new XmlBuffer(int.MaxValue); using (XmlDictionaryWriter writer = _buffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); await this.WriteToAsync(writer); writer.WriteEndElement(); } _buffer.CloseSection(); _buffer.Close(); _bufferElementIndex = 0; } } private void EnsureOuterNameAndNs() { Debug.Assert(_extensionDataWriter != null, "outer name is null only for datacontract and xmlserializer cases"); _extensionDataWriter.ComputeOuterNameAndNs(out _outerName, out _outerNamespace); } // this class holds the extension data and the associated serializer (either DataContractSerializer or XmlSerializer but not both) private class ExtensionDataWriter { private readonly XmlObjectSerializer _dataContractSerializer; private readonly object _extensionData; private readonly string _outerName; private readonly string _outerNamespace; private readonly XmlSerializer _xmlSerializer; public ExtensionDataWriter(object extensionData, XmlObjectSerializer dataContractSerializer, string outerName, string outerNamespace) { Debug.Assert(extensionData != null && dataContractSerializer != null, "null check"); _dataContractSerializer = dataContractSerializer; _extensionData = extensionData; _outerName = outerName; _outerNamespace = outerNamespace; } public ExtensionDataWriter(object extensionData, XmlSerializer serializer) { Debug.Assert(extensionData != null && serializer != null, "null check"); _xmlSerializer = serializer; _extensionData = extensionData; } public void WriteToAsync(XmlWriter writer) { if (_xmlSerializer != null) { Debug.Assert((_dataContractSerializer == null && _outerName == null && _outerNamespace == null), "Xml serializer cannot have outer name, ns"); _xmlSerializer.Serialize(writer, _extensionData); } else { Debug.Assert(_xmlSerializer == null, "Xml serializer cannot be configured"); writer = XmlWriterWrapper.CreateFromWriter(writer); if (_outerName != null) { writer.WriteStartElementAsync(_outerName, _outerNamespace); _dataContractSerializer.WriteObjectContent(writer, _extensionData); writer.WriteEndElementAsync(); } else { _dataContractSerializer.WriteObject(writer, _extensionData); } } } internal void ComputeOuterNameAndNs(out string name, out string ns) { if (_outerName != null) { Debug.Assert(_xmlSerializer == null, "outer name is not null for data contract extension only"); name = _outerName; ns = _outerNamespace; } else if (_dataContractSerializer != null) { Debug.Assert(_xmlSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); XsdDataContractExporter dcExporter = new XsdDataContractExporter(); XmlQualifiedName qName = dcExporter.GetRootElementName(_extensionData.GetType()); if (qName != null) { name = qName.Name; ns = qName.Namespace; } else { // this can happen if an IXmlSerializable type is specified with IsAny=true ReadOuterNameAndNs(out name, out ns); } } else { Debug.Assert(_dataContractSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(_extensionData.GetType()); if (typeMapping != null && !string.IsNullOrEmpty(typeMapping.ElementName)) { name = typeMapping.ElementName; ns = typeMapping.Namespace; } else { // this can happen if an IXmlSerializable type is specified with IsAny=true ReadOuterNameAndNs(out name, out ns); } } } internal void ReadOuterNameAndNs(out string name, out string ns) { using (MemoryStream stream = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(stream)) { this.WriteToAsync(writer); } stream.Seek(0, SeekOrigin.Begin); using (XmlReader reader = XmlReader.Create(stream)) { SyndicationFeedFormatter.MoveToStartElement(reader); name = reader.LocalName; ns = reader.NamespaceURI; } } } } } }
using NSubstitute; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Logging; using NuKeeper.Abstractions.Output; using NuKeeper.Collaboration; using NuKeeper.Commands; using NuKeeper.GitHub; using NuKeeper.Inspection.Logging; using NUnit.Framework; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using NuKeeper.Abstractions.Git; using NuKeeper.AzureDevOps; namespace NuKeeper.Tests.Commands { [TestFixture] public class OrganisationCommandTests { private static CollaborationFactory GetCollaborationFactory(Func<IGitDiscoveryDriver, IEnvironmentVariablesProvider, ISettingsReader> createSettingsReader) { var environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>(); var httpClientFactory = Substitute.For<IHttpClientFactory>(); httpClientFactory.CreateClient().Returns(new HttpClient()); return new CollaborationFactory( new ISettingsReader[] { createSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider) }, Substitute.For<INuKeeperLogger>(), httpClientFactory ); } [Test] public async Task ShouldCallEngineAndNotSucceedWithoutParams() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e)); var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory); var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(-1)); await engine .DidNotReceive() .Run(Arg.Any<SettingsContainer>()); } [Test] public async Task ShouldCallEngineAndSucceedWithRequiredGithubParams() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e)); var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory); command.PersonalAccessToken = "abc"; command.OrganisationName = "testOrg"; var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(0)); await engine .Received(1) .Run(Arg.Any<SettingsContainer>()); } [Test] public async Task ShouldCallEngineAndSucceedWithRequiredAzureDevOpsParams() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var collaborationFactory = GetCollaborationFactory((d, e) => new AzureDevOpsSettingsReader(d, e)); var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory); command.PersonalAccessToken = "abc"; command.OrganisationName = "testOrg"; command.ApiEndpoint = "https://dev.azure.com/org"; var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(0)); await engine .Received(1) .Run(Arg.Any<SettingsContainer>()); } [Test] public async Task ShouldPopulateSettings() { var fileSettings = FileSettings.Empty(); var (settings, platformSettings) = await CaptureSettings(fileSettings); Assert.That(platformSettings, Is.Not.Null); Assert.That(platformSettings.Token, Is.Not.Null); Assert.That(platformSettings.Token, Is.EqualTo("testToken")); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Scope, Is.EqualTo(ServerScope.Organisation)); Assert.That(settings.SourceControlServerSettings.Repository, Is.Null); Assert.That(settings.SourceControlServerSettings.OrganisationName, Is.EqualTo("testOrg")); } [Test] public async Task EmptyFileResultsInDefaultSettings() { var fileSettings = FileSettings.Empty(); var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.UserSettings, Is.Not.Null); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7))); Assert.That(settings.PackageFilters.Excludes, Is.Null); Assert.That(settings.PackageFilters.Includes, Is.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(3)); Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major)); Assert.That(settings.UserSettings.NuGetSources, Is.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text)); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.Null); Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(10)); Assert.That(settings.BranchSettings.DeleteBranchAfterMerge, Is.EqualTo(true)); Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Null); Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Null); } [Test] public async Task WillReadApiFromFile() { var fileSettings = new FileSettings { Api = "http://github.contoso.com/" }; var (_, platformSettings) = await CaptureSettings(fileSettings); Assert.That(platformSettings, Is.Not.Null); Assert.That(platformSettings.BaseApiUrl, Is.Not.Null); Assert.That(platformSettings.BaseApiUrl, Is.EqualTo(new Uri("http://github.contoso.com/"))); } [Test] public async Task WillReadLabelFromFile() { var fileSettings = new FileSettings { Label = new List<string> { "testLabel" } }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(1)); Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("testLabel")); } [Test] public async Task WillReadRepoFiltersFromFile() { var fileSettings = new FileSettings { IncludeRepos = "foo", ExcludeRepos = "bar" }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("foo")); Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("bar")); } [Test] public async Task WillReadMaxPackageUpdatesFromFile() { var fileSettings = new FileSettings { MaxPackageUpdates = 42 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(42)); } [Test] public async Task WillReadMaxRepoFromFile() { var fileSettings = new FileSettings { MaxRepo = 42 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(42)); } [Test] public async Task WillReadBranchNamePrefixFromFile() { var testTemplate = "nukeeper/MyBranch"; var fileSettings = new FileSettings { BranchNameTemplate = testTemplate }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.EqualTo(testTemplate)); } [Test] public async Task CommandLineWillOverrideIncludeRepo() { var fileSettings = new FileSettings { IncludeRepos = "foo", ExcludeRepos = "bar" }; var (settings, _) = await CaptureSettings(fileSettings, true); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("IncludeFromCommand")); Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("bar")); } [Test] public async Task CommandLineWillOverrideExcludeRepo() { var fileSettings = new FileSettings { IncludeRepos = "foo", ExcludeRepos = "bar" }; var (settings, _) = await CaptureSettings(fileSettings, false, true); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("foo")); Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("ExcludeFromCommand")); } [Test] public async Task CommandLineWillOverrideForkMode() { var (_, platformSettings) = await CaptureSettings(FileSettings.Empty(), false, false, null, ForkMode.PreferSingleRepository); Assert.That(platformSettings, Is.Not.Null); Assert.That(platformSettings.ForkMode, Is.Not.Null); Assert.That(platformSettings.ForkMode, Is.EqualTo(ForkMode.PreferSingleRepository)); } [Test] public async Task CommandLineWillOverrideMaxRepo() { var fileSettings = new FileSettings { MaxRepo = 12, }; var (settings, _) = await CaptureSettings(fileSettings, false, true, 22); Assert.That(settings, Is.Not.Null); Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(22)); } public static async Task<(SettingsContainer fileSettings, CollaborationPlatformSettings platformSettings)> CaptureSettings( FileSettings settingsIn, bool addCommandRepoInclude = false, bool addCommandRepoExclude = false, int? maxRepo = null, ForkMode? forkMode = null) { var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); SettingsContainer settingsOut = null; var engine = Substitute.For<ICollaborationEngine>(); await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x)); fileSettings.GetSettings().Returns(settingsIn); var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e)); var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory); command.PersonalAccessToken = "testToken"; command.OrganisationName = "testOrg"; if (addCommandRepoInclude) { command.IncludeRepos = "IncludeFromCommand"; } if (addCommandRepoExclude) { command.ExcludeRepos = "ExcludeFromCommand"; } if (forkMode != null) { command.ForkMode = forkMode; } command.MaxRepositoriesChanged = maxRepo; await command.OnExecute(); return (settingsOut, collaborationFactory.Settings); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SelectManyQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// SelectMany is effectively a nested loops join. It is given two data sources, an /// outer and an inner -- actually, the inner is sometimes calculated by invoking a /// function for each outer element -- and we walk the outer, walking the entire /// inner enumerator for each outer element. There is an optional result selector /// function which can transform the output before yielding it as a result element. /// /// Notes: /// Although select many takes two enumerable objects as input, it appears to the /// query analysis infrastructure as a unary operator. That's because it works a /// little differently than the other binary operators: it has to re-open the right /// child every time an outer element is walked. The right child is NOT partitioned. /// </summary> /// <typeparam name="TLeftInput"></typeparam> /// <typeparam name="TRightInput"></typeparam> /// <typeparam name="TOutput"></typeparam> internal sealed class SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> : UnaryQueryOperator<TLeftInput, TOutput> { private readonly Func<TLeftInput, IEnumerable<TRightInput>> _rightChildSelector; // To select a new child each iteration. private readonly Func<TLeftInput, int, IEnumerable<TRightInput>> _indexedRightChildSelector; // To select a new child each iteration. private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // An optional result selection function. private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool _limitsParallelism = false; // Whether to prematurely merge the input of this operator. //--------------------------------------------------------------------------------------- // Initializes a new select-many operator. // // Arguments: // leftChild - the left data source from which to pull data. // rightChild - the right data source from which to pull data. // rightChildSelector - if no right data source was supplied, the selector function // will generate a new right child for every unique left element. // resultSelector - a selection function for creating output elements. // internal SelectManyQueryOperator(IEnumerable<TLeftInput> leftChild, Func<TLeftInput, IEnumerable<TRightInput>> rightChildSelector, Func<TLeftInput, int, IEnumerable<TRightInput>> indexedRightChildSelector, Func<TLeftInput, TRightInput, TOutput> resultSelector) : base(leftChild) { Debug.Assert(leftChild != null, "left child data source cannot be null"); Debug.Assert(rightChildSelector != null || indexedRightChildSelector != null, "either right child data or selector must be supplied"); Debug.Assert(rightChildSelector == null || indexedRightChildSelector == null, "either indexed- or non-indexed child selector must be supplied (not both)"); Debug.Assert(typeof(TRightInput) == typeof(TOutput) || resultSelector != null, "right input and output must be the same types, otherwise the result selector may not be null"); _rightChildSelector = rightChildSelector; _indexedRightChildSelector = indexedRightChildSelector; _resultSelector = resultSelector; // If the SelectMany is indexed, elements must be returned in the order in which // indices were assigned. _outputOrdered = Child.OutputOrdered || indexedRightChildSelector != null; InitOrderIndex(); } private void InitOrderIndex() { OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (_indexedRightChildSelector != null) { // If this is an indexed SelectMany, we need the order keys to be Correct, so that we can pass them // into the user delegate. _prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct); _limitsParallelism = _prematureMerge && childIndexState != OrdinalIndexState.Shuffled; } else { if (OutputOrdered) { // If the output of this SelectMany is ordered, the input keys must be at least increasing. The // SelectMany algorithm assumes that there will be no duplicate order keys, so if the order keys // are Shuffled, we need to merge prematurely. _prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Increasing); } } SetOrdinalIndexState(OrdinalIndexState.Increasing); } internal override void WrapPartitionedStream<TLeftKey>( PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; if (_indexedRightChildSelector != null) { PartitionedStream<TLeftInput, int> inputStreamInt; // If the index is not correct, we need to reindex. if (_prematureMerge) { ListQueryResults<TLeftInput> listResults = QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings); inputStreamInt = listResults.GetPartitionedStream(); } else { inputStreamInt = (PartitionedStream<TLeftInput, int>)(object)inputStream; } WrapPartitionedStreamIndexed(inputStreamInt, recipient, settings); return; } // // if (_prematureMerge) { PartitionedStream<TLeftInput, int> inputStreamInt = QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings) .GetPartitionedStream(); WrapPartitionedStreamNotIndexed(inputStreamInt, recipient, settings); } else { WrapPartitionedStreamNotIndexed(inputStream, recipient, settings); } } /// <summary> /// A helper method for WrapPartitionedStream. We use the helper to reuse a block of code twice, but with /// a different order key type. (If premature merge occurred, the order key type will be "int". Otherwise, /// it will be the same type as "TLeftKey" in WrapPartitionedStream.) /// </summary> private void WrapPartitionedStreamNotIndexed<TLeftKey>( PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; var keyComparer = new PairComparer<TLeftKey, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>()); var outputStream = new PartitionedStream<TOutput, Pair<TLeftKey, int>>(partitionCount, keyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new SelectManyQueryOperatorEnumerator<TLeftKey>(inputStream[i], this, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } /// <summary> /// Similar helper method to WrapPartitionedStreamNotIndexed, except that this one is for the indexed variant /// of SelectMany (i.e., the SelectMany that passes indices into the user sequence-generating delegate) /// </summary> private void WrapPartitionedStreamIndexed( PartitionedStream<TLeftInput, int> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings) { var keyComparer = new PairComparer<int, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>()); var outputStream = new PartitionedStream<TOutput, Pair<int, int>>(inputStream.PartitionCount, keyComparer, OrdinalIndexState); for (int i = 0; i < inputStream.PartitionCount; i++) { outputStream[i] = new IndexedSelectManyQueryOperatorEnumerator(inputStream[i], this, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the left child and wrapping with a // partition if needed. The right child is not opened yet -- this is always done on demand // as the outer elements are enumerated. // internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping) { QueryResults<TLeftInput> childQueryResults = Child.Open(settings, preferStriping); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token) { if (_rightChildSelector != null) { if (_resultSelector != null) { return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector, _resultSelector); } return (IEnumerable<TOutput>)CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector); } else { Debug.Assert(_indexedRightChildSelector != null); if (_resultSelector != null) { return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector, _resultSelector); } return (IEnumerable<TOutput>)CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector); } } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the SelectMany logic. // class IndexedSelectManyQueryOperatorEnumerator : QueryOperatorEnumerator<TOutput, Pair<int, int>> { private readonly QueryOperatorEnumerator<TLeftInput, int> _leftSource; // The left data source to enumerate. private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use. private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using. private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector). private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing] private readonly CancellationToken _cancellationToken; private class Mutables { internal int _currentRightSourceIndex = -1; // The index for the right data source. internal TLeftInput _currentLeftElement; // The current element in the left data source. internal int _currentLeftSourceIndex; // The current key in the left data source. internal int _lhsCount; //counts the number of lhs elements enumerated. used for cancellation testing. } //--------------------------------------------------------------------------------------- // Instantiates a new select-many enumerator. Notice that the right data source is an // enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left // data source. // internal IndexedSelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, int> leftSource, SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(selectManyOperator != null); _leftSource = leftSource; _selectManyOperator = selectManyOperator; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TOutput currentElement, ref Pair<int, int> currentKey) { while (true) { if (_currentRightSource == null) { _mutables = new Mutables(); // Check cancellation every few lhs-enumerations in case none of them are producing // any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks. if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // We don't have a "current" right enumerator to use. We have to fetch the next // one. If the left has run out of elements, however, we're done and just return // false right away. if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftSourceIndex)) { return false; } // Use the source selection routine to create a right child. IEnumerable<TRightInput> rightChild = _selectManyOperator._indexedRightChildSelector(_mutables._currentLeftElement, _mutables._currentLeftSourceIndex); Debug.Assert(rightChild != null); _currentRightSource = rightChild.GetEnumerator(); Debug.Assert(_currentRightSource != null); // If we have no result selector, we will need to access the Current element of the right // data source as though it is a TOutput. Unfortunately, we know that TRightInput must // equal TOutput (we check it during operator construction), but the type system doesn't. // Thus we would have to cast the result of invoking Current from type TRightInput to // TOutput. This is no good, since the results could be value types. Instead, we save the // enumerator object as an IEnumerator<TOutput> and access that later on. if (_selectManyOperator._resultSelector == null) { _currentRightSourceAsOutput = (IEnumerator<TOutput>)_currentRightSource; Debug.Assert(_currentRightSourceAsOutput == _currentRightSource, "these must be equal, otherwise the surrounding logic will be broken"); } } if (_currentRightSource.MoveNext()) { _mutables._currentRightSourceIndex++; // If the inner data source has an element, we can yield it. if (_selectManyOperator._resultSelector != null) { // In the case of a selection function, use that to yield the next element. currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current); } else { // Otherwise, the right input and output types must be the same. We use the // casted copy of the current right source and just return its current element. Debug.Assert(_currentRightSourceAsOutput != null); currentElement = _currentRightSourceAsOutput.Current; } currentKey = new Pair<int, int>(_mutables._currentLeftSourceIndex, _mutables._currentRightSourceIndex); return true; } else { // Otherwise, we have exhausted the right data source. Loop back around and try // to get the next left element, then its right, and so on. _currentRightSource.Dispose(); _currentRightSource = null; _currentRightSourceAsOutput = null; } } } protected override void Dispose(bool disposing) { _leftSource.Dispose(); if (_currentRightSource != null) { _currentRightSource.Dispose(); } } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the SelectMany logic. // class SelectManyQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TOutput, Pair<TLeftKey, int>> { private readonly QueryOperatorEnumerator<TLeftInput, TLeftKey> _leftSource; // The left data source to enumerate. private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use. private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using. private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector). private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing] private readonly CancellationToken _cancellationToken; private class Mutables { internal int _currentRightSourceIndex = -1; // The index for the right data source. internal TLeftInput _currentLeftElement; // The current element in the left data source. internal TLeftKey _currentLeftKey; // The current key in the left data source. internal int _lhsCount; // Counts the number of lhs elements enumerated. used for cancellation testing. } //--------------------------------------------------------------------------------------- // Instantiates a new select-many enumerator. Notice that the right data source is an // enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left // data source. // internal SelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, TLeftKey> leftSource, SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(selectManyOperator != null); _leftSource = leftSource; _selectManyOperator = selectManyOperator; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TOutput currentElement, ref Pair<TLeftKey, int> currentKey) { while (true) { if (_currentRightSource == null) { _mutables = new Mutables(); // Check cancellation every few lhs-enumerations in case none of them are producing // any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks. if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // We don't have a "current" right enumerator to use. We have to fetch the next // one. If the left has run out of elements, however, we're done and just return // false right away. if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftKey)) { return false; } // Use the source selection routine to create a right child. IEnumerable<TRightInput> rightChild = _selectManyOperator._rightChildSelector(_mutables._currentLeftElement); Debug.Assert(rightChild != null); _currentRightSource = rightChild.GetEnumerator(); Debug.Assert(_currentRightSource != null); // If we have no result selector, we will need to access the Current element of the right // data source as though it is a TOutput. Unfortunately, we know that TRightInput must // equal TOutput (we check it during operator construction), but the type system doesn't. // Thus we would have to cast the result of invoking Current from type TRightInput to // TOutput. This is no good, since the results could be value types. Instead, we save the // enumerator object as an IEnumerator<TOutput> and access that later on. if (_selectManyOperator._resultSelector == null) { _currentRightSourceAsOutput = (IEnumerator<TOutput>)_currentRightSource; Debug.Assert(_currentRightSourceAsOutput == _currentRightSource, "these must be equal, otherwise the surrounding logic will be broken"); } } if (_currentRightSource.MoveNext()) { _mutables._currentRightSourceIndex++; // If the inner data source has an element, we can yield it. if (_selectManyOperator._resultSelector != null) { // In the case of a selection function, use that to yield the next element. currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current); } else { // Otherwise, the right input and output types must be the same. We use the // casted copy of the current right source and just return its current element. Debug.Assert(_currentRightSourceAsOutput != null); currentElement = _currentRightSourceAsOutput.Current; } currentKey = new Pair<TLeftKey, int>(_mutables._currentLeftKey, _mutables._currentRightSourceIndex); return true; } else { // Otherwise, we have exhausted the right data source. Loop back around and try // to get the next left element, then its right, and so on. _currentRightSource.Dispose(); _currentRightSource = null; _currentRightSourceAsOutput = null; } } } protected override void Dispose(bool disposing) { _leftSource.Dispose(); if (_currentRightSource != null) { _currentRightSource.Dispose(); } } } } }
using System.Globalization; using System.Numerics; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Text; using Autofac; using Miningcore.Blockchain.Bitcoin; using Miningcore.Blockchain.Ethereum.Configuration; using Miningcore.Blockchain.Ethereum.DaemonResponses; using Miningcore.Configuration; using Miningcore.Crypto.Hashing.Ethash; using Miningcore.Extensions; using Miningcore.JsonRpc; using Miningcore.Messaging; using Miningcore.Notifications.Messages; using Miningcore.Stratum; using Miningcore.Time; using Miningcore.Util; using Newtonsoft.Json; using NLog; using Block = Miningcore.Blockchain.Ethereum.DaemonResponses.Block; using Contract = Miningcore.Contracts.Contract; using EC = Miningcore.Blockchain.Ethereum.EthCommands; using static Miningcore.Util.ActionUtils; using System.Reactive; namespace Miningcore.Blockchain.Ethereum; public class EthereumJobManager : JobManagerBase<EthereumJob> { public EthereumJobManager( IComponentContext ctx, IMasterClock clock, IMessageBus messageBus, IExtraNonceProvider extraNonceProvider, JsonSerializerSettings serializerSettings) : base(ctx, messageBus) { Contract.RequiresNonNull(ctx, nameof(ctx)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(messageBus, nameof(messageBus)); Contract.RequiresNonNull(extraNonceProvider, nameof(extraNonceProvider)); this.clock = clock; this.extraNonceProvider = extraNonceProvider; serializer = new JsonSerializer { ContractResolver = serializerSettings.ContractResolver }; } private DaemonEndpointConfig[] daemonEndpoints; private RpcClient rpcClient; private EthereumNetworkType networkType; private GethChainType chainType; private EthashFull ethash; private readonly IMasterClock clock; private readonly IExtraNonceProvider extraNonceProvider; private const int MaxBlockBacklog = 3; protected readonly Dictionary<string, EthereumJob> validJobs = new(); private EthereumPoolConfigExtra extraPoolConfig; private readonly JsonSerializer serializer; protected async Task<bool> UpdateJob(CancellationToken ct, string via = null) { logger.LogInvoke(); try { return UpdateJob(await GetBlockTemplateAsync(ct), via); } catch(Exception ex) { logger.Error(ex, () => $"Error during {nameof(UpdateJob)}"); } return false; } protected bool UpdateJob(EthereumBlockTemplate blockTemplate, string via = null) { logger.LogInvoke(); try { // may happen if daemon is currently not connected to peers if(blockTemplate == null || blockTemplate.Header?.Length == 0) return false; var job = currentJob; var isNew = currentJob == null || job.BlockTemplate.Height < blockTemplate.Height || job.BlockTemplate.Header != blockTemplate.Header; if(isNew) { messageBus.NotifyChainHeight(poolConfig.Id, blockTemplate.Height, poolConfig.Template); var jobId = NextJobId("x8"); // update template job = new EthereumJob(jobId, blockTemplate, logger); lock(jobLock) { // add jobs validJobs[jobId] = job; // remove old ones var obsoleteKeys = validJobs.Keys .Where(key => validJobs[key].BlockTemplate.Height < job.BlockTemplate.Height - MaxBlockBacklog).ToArray(); foreach(var key in obsoleteKeys) validJobs.Remove(key); } currentJob = job; logger.Info(() => $"New work at height {currentJob.BlockTemplate.Height} and header {currentJob.BlockTemplate.Header} via [{(via ?? "Unknown")}]"); // update stats BlockchainStats.LastNetworkBlockTime = clock.Now; BlockchainStats.BlockHeight = job.BlockTemplate.Height; BlockchainStats.NetworkDifficulty = job.BlockTemplate.Difficulty; BlockchainStats.NextNetworkTarget = job.BlockTemplate.Target; BlockchainStats.NextNetworkBits = ""; } return isNew; } catch(Exception ex) { logger.Error(ex, () => $"Error during {nameof(UpdateJob)}"); } return false; } private async Task<EthereumBlockTemplate> GetBlockTemplateAsync(CancellationToken ct) { logger.LogInvoke(); var requests = new[] { new RpcRequest(EC.GetWork), new RpcRequest(EC.GetBlockByNumber, new[] { (object) "latest", true }) }; var responses = await rpcClient.ExecuteBatchAsync(logger, ct, requests); if(responses.Any(x => x.Error != null)) { logger.Warn(() => $"Error(s) refreshing blocktemplate: {responses.First(x => x.Error != null).Error.Message}"); return null; } // extract results var work = responses[0].Response.ToObject<string[]>(); var block = responses[1].Response.ToObject<Block>(); // append blockheight (Recent versions of geth return this as the 4th element in the getWork response, older geth does not) if(work.Length < 4) { var currentHeight = block.Height.Value; work = work.Concat(new[] { (currentHeight + 1).ToStringHexWithPrefix() }).ToArray(); } // extract values var height = work[3].IntegralFromHex<ulong>(); var targetString = work[2]; var target = BigInteger.Parse(targetString.Substring(2), NumberStyles.HexNumber); var result = new EthereumBlockTemplate { Header = work[0], Seed = work[1], Target = targetString, Difficulty = (ulong) BigInteger.Divide(EthereumConstants.BigMaxValue, target), Height = height }; return result; } private async Task ShowDaemonSyncProgressAsync(CancellationToken ct) { var syncStateResponse = await rpcClient.ExecuteAsync<object>(logger, EC.GetSyncState, ct); if(syncStateResponse.Error == null) { // eth_syncing returns false if not synching if(syncStateResponse.Response is false) return; if(syncStateResponse.Response is SyncState syncState) { // get peer count var getPeerCountResponse = await rpcClient.ExecuteAsync<string>(logger, EC.GetPeerCount, ct); var peerCount = getPeerCountResponse.Response.IntegralFromHex<uint>(); if(syncState.WarpChunksAmount != 0) { var warpChunkAmount = syncState.WarpChunksAmount; var warpChunkProcessed = syncState.WarpChunksProcessed; var percent = (double) warpChunkProcessed / warpChunkAmount * 100; logger.Info(() => $"Daemons have downloaded {percent:0.00}% of warp-chunks from {peerCount} peers"); } else if(syncState.HighestBlock != 0) { var lowestHeight = syncState.CurrentBlock; var totalBlocks = syncState.HighestBlock; var percent = (double) lowestHeight / totalBlocks * 100; logger.Info(() => $"Daemons have downloaded {percent:0.00}% of blockchain from {peerCount} peers"); } } } } private async Task UpdateNetworkStatsAsync(CancellationToken ct) { logger.LogInvoke(); try { var requests = new[] { new RpcRequest(EC.GetPeerCount), new RpcRequest(EC.GetBlockByNumber, new[] { (object) "latest", true }) }; var responses = await rpcClient.ExecuteBatchAsync(logger, ct, requests); if(responses.Any(x => x.Error != null)) { var errors = responses.Where(x => x.Error != null) .ToArray(); if(errors.Any()) logger.Warn(() => $"Error(s) refreshing network stats: {string.Join(", ", errors.Select(y => y.Error.Message))})"); } // extract results var peerCount = responses[0].Response.ToObject<string>().IntegralFromHex<int>(); var latestBlockInfo = responses[1].Response.ToObject<Block>(); var latestBlockHeight = latestBlockInfo.Height.Value; var latestBlockTimestamp = latestBlockInfo.Timestamp; var latestBlockDifficulty = latestBlockInfo.Difficulty.IntegralFromHex<ulong>(); var sampleSize = (ulong) 300; var sampleBlockNumber = latestBlockHeight - sampleSize; var sampleBlockResults = await rpcClient.ExecuteAsync<Block>(logger, EC.GetBlockByNumber, ct, new[] { (object) sampleBlockNumber.ToStringHexWithPrefix(), true }); var sampleBlockTimestamp = sampleBlockResults.Response.Timestamp; var blockTime = (double) (latestBlockTimestamp - sampleBlockTimestamp) / sampleSize; var networkHashrate = (double) (latestBlockDifficulty / blockTime); BlockchainStats.NetworkHashrate = blockTime > 0 ? networkHashrate : 0; BlockchainStats.ConnectedPeers = peerCount; } catch(Exception e) { logger.Error(e); } } private async Task<bool> SubmitBlockAsync(Share share, string fullNonceHex, string headerHash, string mixHash) { // submit work var response = await rpcClient.ExecuteAsync<object>(logger, EC.SubmitWork, CancellationToken.None, new[] { fullNonceHex, headerHash, mixHash }); if(response.Error != null || (bool?) response.Response == false) { var error = response.Error?.Message ?? response?.Response?.ToString(); logger.Warn(() => $"Block {share.BlockHeight} submission failed with: {error}"); messageBus.SendMessage(new AdminNotification("Block submission failed", $"Pool {poolConfig.Id} {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}failed to submit block {share.BlockHeight}: {error}")); return false; } return true; } private object[] GetJobParamsForStratum(bool isNew) { var job = currentJob; if(job != null) { return new object[] { job.Id, job.BlockTemplate.Seed.StripHexPrefix(), job.BlockTemplate.Header.StripHexPrefix(), isNew }; } return new object[0]; } #region API-Surface public IObservable<object> Jobs { get; private set; } public override void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig) { extraPoolConfig = poolConfig.Extra.SafeExtensionDataAs<EthereumPoolConfigExtra>(); // extract standard daemon endpoints daemonEndpoints = poolConfig.Daemons .Where(x => string.IsNullOrEmpty(x.Category)) .ToArray(); base.Configure(poolConfig, clusterConfig); if(poolConfig.EnableInternalStratum == true) { // ensure dag location is configured var dagDir = !string.IsNullOrEmpty(extraPoolConfig?.DagDir) ? Environment.ExpandEnvironmentVariables(extraPoolConfig.DagDir) : Dag.GetDefaultDagDirectory(); // create it if necessary Directory.CreateDirectory(dagDir); // setup ethash ethash = new EthashFull(3, dagDir); } } public bool ValidateAddress(string address) { if(string.IsNullOrEmpty(address)) return false; if(EthereumConstants.ZeroHashPattern.IsMatch(address) || !EthereumConstants.ValidAddressPattern.IsMatch(address)) return false; return true; } public void PrepareWorker(StratumConnection client) { var context = client.ContextAs<EthereumWorkerContext>(); context.ExtraNonce1 = extraNonceProvider.Next(); } public async ValueTask<Share> SubmitShareAsync(StratumConnection worker, string[] request, CancellationToken ct) { Contract.RequiresNonNull(worker, nameof(worker)); Contract.RequiresNonNull(request, nameof(request)); logger.LogInvoke(new object[] { worker.ConnectionId }); var context = worker.ContextAs<EthereumWorkerContext>(); // var miner = request[0]; var jobId = request[1]; var nonce = request[2]; EthereumJob job; // stale? lock(jobLock) { if(!validJobs.TryGetValue(jobId, out job)) throw new StratumException(StratumError.MinusOne, "stale share"); } // validate & process var (share, fullNonceHex, headerHash, mixHash) = await job.ProcessShareAsync(worker, nonce, ethash, ct); // enrich share with common data share.PoolId = poolConfig.Id; share.NetworkDifficulty = BlockchainStats.NetworkDifficulty; share.Source = clusterConfig.ClusterName; share.Created = clock.Now; // if block candidate, submit & check if accepted by network if(share.IsBlockCandidate) { logger.Info(() => $"Submitting block {share.BlockHeight}"); share.IsBlockCandidate = await SubmitBlockAsync(share, fullNonceHex, headerHash, mixHash); if(share.IsBlockCandidate) { logger.Info(() => $"Daemon accepted block {share.BlockHeight} submitted by {context.Miner}"); OnBlockFound(); } } return share; } public BlockchainStats BlockchainStats { get; } = new(); #endregion // API-Surface #region Overrides protected override void ConfigureDaemons() { var jsonSerializerSettings = ctx.Resolve<JsonSerializerSettings>(); rpcClient = new RpcClient(daemonEndpoints.First(), jsonSerializerSettings, messageBus, poolConfig.Id); } protected override async Task<bool> AreDaemonsHealthyAsync(CancellationToken ct) { var response = await rpcClient.ExecuteAsync<Block>(logger, EC.GetBlockByNumber, ct, new[] { (object) "latest", true }); return response.Error == null; } protected override async Task<bool> AreDaemonsConnectedAsync(CancellationToken ct) { var response = await rpcClient.ExecuteAsync<string>(logger, EC.GetPeerCount, ct); return response.Error == null && response.Response.IntegralFromHex<uint>() > 0; } protected override async Task EnsureDaemonsSynchedAsync(CancellationToken ct) { var syncPendingNotificationShown = false; while(true) { var responses = await rpcClient.ExecuteAsync<object>(logger, EC.GetSyncState, ct); var isSynched = responses.Response is false; if(isSynched) { logger.Info(() => "All daemons synched with blockchain"); break; } if(!syncPendingNotificationShown) { logger.Info(() => "Daemons still syncing with network. Manager will be started once synced"); syncPendingNotificationShown = true; } await ShowDaemonSyncProgressAsync(ct); // delay retry by 5s await Task.Delay(5000, ct); } } protected override async Task PostStartInitAsync(CancellationToken ct) { var requests = new[] { new RpcRequest(EC.GetNetVersion), new RpcRequest(EC.GetAccounts), new RpcRequest(EC.GetCoinbase), }; var responses = await rpcClient.ExecuteBatchAsync(logger, ct, requests); if(responses.Any(x => x.Error != null)) { var errors = responses.Take(3).Where(x => x.Error != null) .ToArray(); if(errors.Any()) logger.ThrowLogPoolStartupException($"Init RPC failed: {string.Join(", ", errors.Select(y => y.Error.Message))}"); } // extract results var netVersion = responses[0].Response.ToObject<string>(); var accounts = responses[1].Response.ToObject<string[]>(); var coinbase = responses[2].Response.ToObject<string>(); var gethChain = extraPoolConfig?.ChainTypeOverride ?? "Ethereum"; EthereumUtils.DetectNetworkAndChain(netVersion, gethChain, out networkType, out chainType); // update stats BlockchainStats.RewardType = "POW"; BlockchainStats.NetworkType = $"{chainType}-{networkType}"; await UpdateNetworkStatsAsync(ct); // Periodically update network stats Observable.Interval(TimeSpan.FromMinutes(10)) .Select(via => Observable.FromAsync(() => Guard(()=> UpdateNetworkStatsAsync(ct), ex=> logger.Error(ex)))) .Concat() .Subscribe(); if(poolConfig.EnableInternalStratum == true) { // make sure we have a current DAG while(true) { var blockTemplate = await GetBlockTemplateAsync(ct); if(blockTemplate != null) { logger.Info(() => "Loading current DAG ..."); await ethash.GetDagAsync(blockTemplate.Height, logger, ct); logger.Info(() => "Loaded current DAG"); break; } logger.Info(() => "Waiting for first valid block template"); await Task.Delay(TimeSpan.FromSeconds(5), ct); } } ConfigureRewards(); await SetupJobUpdates(ct); } private void ConfigureRewards() { // Donation to MiningCore development if(networkType == EthereumNetworkType.Mainnet && chainType == GethChainType.Ethereum && DevDonation.Addresses.TryGetValue(poolConfig.Template.As<CoinTemplate>().Symbol, out var address)) { poolConfig.RewardRecipients = poolConfig.RewardRecipients.Concat(new[] { new RewardRecipient { Address = address, Percentage = DevDonation.Percent, Type = "dev" } }).ToArray(); } } protected virtual async Task SetupJobUpdates(CancellationToken ct) { var pollingInterval = poolConfig.BlockRefreshInterval > 0 ? poolConfig.BlockRefreshInterval : 1000; var blockSubmission = blockFoundSubject.Synchronize(); var pollTimerRestart = blockFoundSubject.Synchronize(); var triggers = new List<IObservable<(string Via, string Data)>> { blockSubmission.Select(x => (JobRefreshBy.BlockFound, (string) null)) }; var enableStreaming = extraPoolConfig?.EnableDaemonWebsocketStreaming == true; var streamingEndpoint = daemonEndpoints .Where(x => x.Extra.SafeExtensionDataAs<EthereumDaemonEndpointConfigExtra>() != null) .Select(x=> Tuple.Create(x, x.Extra.SafeExtensionDataAs<EthereumDaemonEndpointConfigExtra>())) .FirstOrDefault(); if(enableStreaming && streamingEndpoint.Item2?.PortWs.HasValue != true) { logger.Warn(() => $"'{nameof(EthereumPoolConfigExtra.EnableDaemonWebsocketStreaming).ToLowerCamelCase()}' enabled but not a single daemon found with a configured websocket port ('{nameof(EthereumDaemonEndpointConfigExtra.PortWs).ToLowerCamelCase()}'). Falling back to polling."); enableStreaming = false; } if(enableStreaming) { var (endpointConfig, extra) = streamingEndpoint; var wsEndpointConfig = new DaemonEndpointConfig { Host = endpointConfig.Host, Port = extra.PortWs.Value, HttpPath = extra.HttpPathWs, Ssl = extra.SslWs }; logger.Info(() => $"Subscribing to WebSocket {(wsEndpointConfig.Ssl ? "wss" : "ws")}://{wsEndpointConfig.Host}:{wsEndpointConfig.Port}"); var wsSubscription = "newHeads"; var isRetry = false; retry: // stream work updates var getWorkObs = rpcClient.WebsocketSubscribe(logger, ct, wsEndpointConfig, EC.Subscribe, new[] { wsSubscription }) .Publish() .RefCount(); // test subscription var subcriptionResponse = await getWorkObs .Take(1) .Select(x => JsonConvert.DeserializeObject<JsonRpcResponse<string>>(Encoding.UTF8.GetString(x))) .ToTask(ct); if(subcriptionResponse.Error != null) { // older versions of geth only support subscriptions to "newBlocks" if(!isRetry && subcriptionResponse.Error.Code == (int) BitcoinRPCErrorCode.RPC_METHOD_NOT_FOUND) { wsSubscription = "newBlocks"; isRetry = true; goto retry; } logger.ThrowLogPoolStartupException($"Unable to subscribe to geth websocket '{wsSubscription}': {subcriptionResponse.Error.Message} [{subcriptionResponse.Error.Code}]"); } var blockNotify = getWorkObs.Where(x => x != null) .Do(x => Console.WriteLine("** WS")) .Publish() .RefCount(); pollTimerRestart = Observable.Merge( blockSubmission, blockNotify.Select(_ => Unit.Default)) .Publish() .RefCount(); // Websocket triggers.Add(blockNotify .Select(_ => (JobRefreshBy.WebSocket, (string) null))); } triggers.Add(Observable.Timer(TimeSpan.FromMilliseconds(pollingInterval)) .TakeUntil(pollTimerRestart) .Select(_ => (JobRefreshBy.Poll, (string) null)) .Repeat()); Jobs = Observable.Merge(triggers) .Select(x => Observable.FromAsync(() => UpdateJob(ct, x.Via))) .Concat() .Where(isNew => isNew) .Select(_ => GetJobParamsForStratum(true)) .Publish() .RefCount(); } #endregion // Overrides }
using Aspose.Email.Live.Demos.UI.Helpers; using Aspose.Email.Live.Demos.UI.Models; using Aspose.Email.Live.Demos.UI.Services; using Aspose.Email.Live.Demos.UI.Models; using Aspose.Email.Live.Demos.UI.Services.Email; using Aspose.Email; using Aspose.Email.Mapi; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using Aspose.Email.Live.Demos.UI; namespace Aspose.Email.Live.Demos.UI.Controllers { public class AsposeEmailEditorController : AsposeEmailBaseApiController { public AsposeEmailEditorController(ILogger<AsposeEmailEditorController> logger, IConfiguration config, IStorageService storageService, IEmailService emailService) : base(logger, config, storageService, emailService) { } [HttpPost("GetDocumentData")] public async Task<string> GetDocumentData(string fileName, string folderName) { fileName = HttpUtility.HtmlDecode(fileName); if (fileName.IsNullOrWhiteSpace()) throw new BadRequestException("File name not provided"); if (folderName.IsNullOrWhiteSpace()) throw new BadRequestException("Folder name not provided"); using (var fileStream = await StorageService.ReadFile(folderName, fileName)) { return JsonConvert.SerializeObject(EmailService.ParseFileData(fileStream)); } } [HttpPost("UpdateContentsWithAttachments")] public async Task<string> UpdateContentsWithAttachments([FromBody] EditorUpdateContentRequest data) { if (!data.CreateNewFile) { if (data.FileName.IsNullOrWhiteSpace()) throw new BadRequestException("File name not provided"); if (data.FolderName.IsNullOrWhiteSpace()) throw new BadRequestException("Folder name not provided"); } if (data.Htmldata == null) throw new BadRequestException("Html data name not provided"); if (data.OutputType.IsNullOrWhiteSpace()) throw new BadRequestException("Output type name not provided"); if (!data.CreateNewFile) data.FileName = HttpUtility.HtmlDecode(data.FileName); else data.FileName = "New file"; data.OutputType = data.OutputType.ToLower(); var savingFileName = Path.GetFileNameWithoutExtension(data.FileName) + data.OutputType; var uid = Guid.NewGuid().ToString(); try { switch (data.OutputType) { case ".html": await StorageService.SaveFile(data.Htmldata, uid, savingFileName); break; default: { using (var message = await GetMessageFromData(data)) { message.SetBodyContent(data.Htmldata, BodyContentType.Html); var changes = data.AttachmentsData?.Select(x => x.Value).ToArray(); var attachments = message.Attachments.ToArray(); if (changes != null) { for (int i = 0; i < changes.Length; i++) { var ch = changes[i]; if (ch.NeedRemove) message.Attachments.Remove(attachments[ch.Index]); if (ch.WasAdded && ch.Name != null && ch.SourceBase64 != null) message.Attachments.Add(ch.Name, Convert.FromBase64String(ch.SourceBase64)); } } await StorageService.SaveMessage(message, uid, savingFileName, data.OutputType == ".eml" ? EmlSaveOptions.DefaultEml : EmlSaveOptions.DefaultMsgUnicode); break; } } } return JsonConvert.SerializeObject(new Response() { FileName = HttpUtility.UrlEncode(savingFileName), FolderName = uid, StatusCode = 200 }); } catch (Exception ex) { var logMsg = $"ControllerName = {nameof(AsposeEmailEditorController)}, MethodName = {nameof(UpdateContents)}, Folder = {uid}"; Logger.LogError(ex, logMsg, AsposeEmail + EditorApp, savingFileName); return JsonConvert.SerializeObject(new Response() { FileName = HttpUtility.UrlEncode(savingFileName), FolderName = uid, StatusCode = 500, Status = ex.Message }.WithTrace(Configuration, ex)); } } private async Task<MapiMessage> GetMessageFromData(EditorUpdateContentRequest data) { if (data.CreateNewFile) return new MapiMessage(OutlookMessageFormat.Unicode); return await StorageService.ReadMapiMessage(data.FolderName, data.FileName); } [HttpPost("UpdateContents")] public async Task<string> UpdateContents(string fileName, string folderName, string htmldata, string outputType) { if (fileName.IsNullOrWhiteSpace()) throw new BadRequestException("File name not provided"); if (folderName.IsNullOrWhiteSpace()) throw new BadRequestException("Folder name not provided"); if (htmldata == null) throw new BadRequestException("Html data name not provided"); if (outputType.IsNullOrWhiteSpace()) throw new BadRequestException("Output type name not provided"); fileName = HttpUtility.HtmlDecode(fileName); outputType = outputType.ToLower(); var savingFileName = Path.GetFileNameWithoutExtension(fileName) + outputType; var uid = Guid.NewGuid().ToString(); try { switch (outputType) { case ".html": await StorageService.SaveFile(htmldata, uid, savingFileName); break; default: { using (var message = await StorageService.ReadMapiMessage(folderName, fileName)) { message.SetBodyContent(htmldata, BodyContentType.Html); await StorageService.SaveMessage(message, uid, savingFileName, outputType == ".eml" ? EmlSaveOptions.DefaultEml : EmlSaveOptions.DefaultMsgUnicode); break; } } } return JsonConvert.SerializeObject(new Response() { FileName = HttpUtility.UrlEncode(savingFileName), FolderName = uid, StatusCode = 200 }); } catch(Exception ex) { var logMsg = $"ControllerName = {nameof(AsposeEmailEditorController)}, MethodName = {nameof(UpdateContents)}, Folder = {uid}"; Logger.LogError(ex, logMsg, AsposeEmail + EditorApp, savingFileName); return JsonConvert.SerializeObject(new Response() { FileName = HttpUtility.UrlEncode(savingFileName), FolderName = uid, StatusCode = 500, Status = ex.Message }); } } } }
using System; using System.Collections; using System.Collections.Generic; namespace IniParser.Model { /// <summary> /// Represents a collection of Keydata. /// </summary> public class KeyDataCollection : ICloneable, IEnumerable<KeyData> { IEqualityComparer<string> _searchComparer; #region Initialization /// <summary> /// Initializes a new instance of the <see cref="KeyDataCollection"/> class. /// </summary> public KeyDataCollection() :this(EqualityComparer<string>.Default) {} /// <summary> /// Initializes a new instance of the <see cref="KeyDataCollection"/> class with a given /// search comparer /// </summary> /// <param name="searchComparer"> /// Search comparer used to find the key by name in the collection /// </param> public KeyDataCollection(IEqualityComparer<string> searchComparer) { _searchComparer = searchComparer; _keyData = new Dictionary<string, KeyData>(_searchComparer); } /// <summary> /// Initializes a new instance of the <see cref="KeyDataCollection"/> class /// from a previous instance of <see cref="KeyDataCollection"/>. /// </summary> /// <remarks> /// Data from the original KeyDataCollection instance is deeply copied /// </remarks> /// <param name="ori"> /// The instance of the <see cref="KeyDataCollection"/> class /// used to create the new instance. /// </param> public KeyDataCollection(KeyDataCollection ori, IEqualityComparer<string> searchComparer) : this(searchComparer) { foreach ( KeyData key in ori) { if (_keyData.ContainsKey(key.KeyName)) { _keyData[key.KeyName] = key; } else { _keyData.Add(key.KeyName, key); } } } #endregion #region Properties /// <summary> /// Gets or sets the value of a concrete key. /// </summary> /// <remarks> /// If we try to assign the value of a key which doesn't exists, /// a new key is added with the name and the value is assigned to it. /// </remarks> /// <param name="keyName"> /// Name of the key /// </param> /// <returns> /// The string with key's value or null if the key was not found. /// </returns> public string this[string keyName] { get { if (_keyData.ContainsKey(keyName)) return _keyData[keyName].Value; return null; } set { if (!_keyData.ContainsKey(keyName)) { this.AddKey(keyName); } _keyData[keyName].Value = value; } } /// <summary> /// Return the number of keys in the collection /// </summary> public int Count { get { return _keyData.Count; } } #endregion #region Operations /// <summary> /// Adds a new key with the specified name and empty value and comments /// </summary> /// <param name="keyName"> /// New key to be added. /// </param> /// <c>true</c> if the key was added <c>false</c> if a key with the same name already exist /// in the collection /// </returns> public bool AddKey(string keyName) { if ( !_keyData.ContainsKey(keyName) ) { _keyData.Add(keyName, new KeyData(keyName)); return true; } return false; } [Obsolete("Pottentially buggy method! Use AddKey(KeyData keyData) instead (See comments in code for an explanation of the bug)")] public bool AddKey(string keyName, KeyData keyData) { // BUG: this actually can allow you to add the keyData having // keyData.KeyName different from the argument 'keyName' in this method // which doesn't make any sense if (AddKey(keyName)) { _keyData[keyName] = keyData; return true; } return false; } /// <summary> /// Adds a new key to the collection /// </summary> /// <param name="keyData"> /// KeyData instance. /// </param> /// <returns> /// <c>true</c> if the key was added <c>false</c> if a key with the same name already exist /// in the collection /// </returns> public bool AddKey(KeyData keyData) { if (AddKey(keyData.KeyName)) { _keyData[keyData.KeyName] = keyData; return true; } return false; } /// <summary> /// Adds a new key with the specified name and value to the collection /// </summary> /// <param name="keyName"> /// Name of the new key to be added. /// </param> /// <param name="keyValue"> /// Value associated to the key. /// </param> /// <returns> /// <c>true</c> if the key was added <c>false</c> if a key with the same name already exist /// in the collection. /// </returns> public bool AddKey(string keyName, string keyValue) { if (AddKey(keyName)) { _keyData[keyName].Value = keyValue; return true; } return false; } /// <summary> /// Clears all comments of this section /// </summary> public void ClearComments() { foreach(var keydata in this) { keydata.Comments.Clear(); } } /// <summary> /// Gets if a specifyed key name exists in the collection. /// </summary> /// <param name="keyName">Key name to search</param> /// <returns><c>true</c> if a key with the specified name exists in the collectoin /// <c>false</c> otherwise</returns> public bool ContainsKey(string keyName) { return _keyData.ContainsKey(keyName); } /// <summary> /// Retrieves the data for a specified key given its name /// </summary> /// <param name="keyName">Name of the key to retrieve.</param> /// <returns> /// A <see cref="KeyData"/> instance holding /// the key information or <c>null</c> if the key wasn't found. /// </returns> public KeyData GetKeyData(string keyName) { if (_keyData.ContainsKey(keyName)) return _keyData[keyName]; return null; } public void Merge(KeyDataCollection keyDataToMerge) { foreach(var keyData in keyDataToMerge) { AddKey(keyData.KeyName); GetKeyData(keyData.KeyName).Comments.AddRange(keyData.Comments); this[keyData.KeyName] = keyData.Value; } } /// <summary> /// Deletes all keys in this collection. /// </summary> public void RemoveAllKeys() { _keyData.Clear(); } /// <summary> /// Deletes a previously existing key, including its associated data. /// </summary> /// <param name="keyName">The key to be removed.</param> /// <returns> /// <c>true</c> if a key with the specified name was removed /// <c>false</c> otherwise. /// </returns> public bool RemoveKey(string keyName) { return _keyData.Remove(keyName); } /// <summary> /// Sets the key data associated to a specified key. /// </summary> /// <param name="data">The new <see cref="KeyData"/> for the key.</param> public void SetKeyData(KeyData data) { if (data == null) return; if (_keyData.ContainsKey(data.KeyName)) RemoveKey(data.KeyName); AddKey(data); } #endregion #region IEnumerable<KeyData> Members /// <summary> /// Allows iteration througt the collection. /// </summary> /// <returns>A strong-typed IEnumerator </returns> public IEnumerator<KeyData> GetEnumerator() { foreach ( string key in _keyData.Keys ) yield return _keyData[key]; } #region IEnumerable Members /// <summary> /// Implementation needed /// </summary> /// <returns>A weak-typed IEnumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return _keyData.GetEnumerator(); } #endregion #endregion #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public object Clone() { return new KeyDataCollection(this, _searchComparer); } #endregion #region Non-public Members // Hack for getting the last key value (if exists) w/out using LINQ // and maintain support for earlier versions of .NET internal KeyData GetLast() { KeyData result = null; if (_keyData.Keys.Count <=0) return result; foreach( var k in _keyData.Keys) result = _keyData[k]; return result; } /// <summary> /// Collection of KeyData for a given section /// </summary> private readonly Dictionary<string, KeyData> _keyData; #endregion } }
using J2N.Numerics; using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Util { /* * 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 DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; /// <summary> /// BitSet of fixed length (numBits), backed by accessible (<see cref="GetBits()"/>) /// long[], accessed with an int index, implementing <see cref="GetBits()"/> and /// <see cref="DocIdSet"/>. If you need to manage more than 2.1B bits, use /// <see cref="Int64BitSet"/>. /// <para/> /// @lucene.internal /// </summary> public sealed class FixedBitSet : DocIdSet, IBits { /// <summary> /// A <see cref="DocIdSetIterator"/> which iterates over set bits in a /// <see cref="FixedBitSet"/>. /// </summary> public sealed class FixedBitSetIterator : DocIdSetIterator { internal readonly int numBits, numWords; internal readonly long[] bits; internal int doc = -1; /// <summary> /// Creates an iterator over the given <see cref="FixedBitSet"/>. </summary> public FixedBitSetIterator(FixedBitSet bits) : this(bits.bits, bits.numBits, bits.numWords) { } /// <summary> /// Creates an iterator over the given array of bits. </summary> public FixedBitSetIterator(long[] bits, int numBits, int wordLength) { this.bits = bits; this.numBits = numBits; this.numWords = wordLength; } public override int NextDoc() { if (doc == NO_MORE_DOCS || ++doc >= numBits) { return doc = NO_MORE_DOCS; } int i = doc >> 6; int subIndex = doc & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word != 0) { return doc = doc + word.TrailingZeroCount(); } while (++i < numWords) { word = bits[i]; if (word != 0) { return doc = (i << 6) + word.TrailingZeroCount(); } } return doc = NO_MORE_DOCS; } public override int DocID => doc; public override long GetCost() { return numBits; } public override int Advance(int target) { if (doc == NO_MORE_DOCS || target >= numBits) { return doc = NO_MORE_DOCS; } int i = target >> 6; int subIndex = target & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word != 0) { return doc = target + word.TrailingZeroCount(); } while (++i < numWords) { word = bits[i]; if (word != 0) { return doc = (i << 6) + word.TrailingZeroCount(); } } return doc = NO_MORE_DOCS; } } /// <summary> /// If the given <see cref="FixedBitSet"/> is large enough to hold <paramref name="numBits"/>, /// returns the given bits, otherwise returns a new <see cref="FixedBitSet"/> which /// can hold the requested number of bits. /// /// <para/> /// <b>NOTE:</b> the returned bitset reuses the underlying <see cref="T:long[]"/> of /// the given <paramref name="bits"/> if possible. Also, calling <see cref="Length"/> on the /// returned bits may return a value greater than <paramref name="numBits"/>. /// </summary> public static FixedBitSet EnsureCapacity(FixedBitSet bits, int numBits) { if (numBits < bits.Length) { return bits; } else { int numWords = Bits2words(numBits); long[] arr = bits.GetBits(); if (numWords >= arr.Length) { arr = ArrayUtil.Grow(arr, numWords + 1); } return new FixedBitSet(arr, arr.Length << 6); } } /// <summary> /// Returns the number of 64 bit words it would take to hold <paramref name="numBits"/> </summary> public static int Bits2words(int numBits) { int numLong = (int)((uint)numBits >> 6); if ((numBits & 63) != 0) { numLong++; } return numLong; } /// <summary> /// Returns the popcount or cardinality of the intersection of the two sets. /// Neither set is modified. /// </summary> public static long IntersectionCount(FixedBitSet a, FixedBitSet b) { return BitUtil.Pop_Intersect(a.bits, b.bits, 0, Math.Min(a.numWords, b.numWords)); } /// <summary> /// Returns the popcount or cardinality of the union of the two sets. Neither /// set is modified. /// </summary> public static long UnionCount(FixedBitSet a, FixedBitSet b) { long tot = BitUtil.Pop_Union(a.bits, b.bits, 0, Math.Min(a.numWords, b.numWords)); if (a.numWords < b.numWords) { tot += BitUtil.Pop_Array(b.bits, a.numWords, b.numWords - a.numWords); } else if (a.numWords > b.numWords) { tot += BitUtil.Pop_Array(a.bits, b.numWords, a.numWords - b.numWords); } return tot; } /// <summary> /// Returns the popcount or cardinality of "a and not b" or /// "intersection(a, not(b))". Neither set is modified. /// </summary> public static long AndNotCount(FixedBitSet a, FixedBitSet b) { long tot = BitUtil.Pop_AndNot(a.bits, b.bits, 0, Math.Min(a.numWords, b.numWords)); if (a.numWords > b.numWords) { tot += BitUtil.Pop_Array(a.bits, b.numWords, a.numWords - b.numWords); } return tot; } internal readonly long[] bits; internal readonly int numBits; internal readonly int numWords; public FixedBitSet(int numBits) { this.numBits = numBits; bits = new long[Bits2words(numBits)]; numWords = bits.Length; } public FixedBitSet(long[] storedBits, int numBits) { this.numWords = Bits2words(numBits); if (numWords > storedBits.Length) { throw new ArgumentException("The given long array is too small to hold " + numBits + " bits"); } this.numBits = numBits; this.bits = storedBits; } public override DocIdSetIterator GetIterator() { return new FixedBitSetIterator(bits, numBits, numWords); } public override IBits Bits => this; public int Length => numBits; /// <summary> /// This DocIdSet implementation is cacheable. </summary> public override bool IsCacheable => true; /// <summary> /// Expert. </summary> [WritableArray] public long[] GetBits() { return bits; } /// <summary> /// Returns number of set bits. NOTE: this visits every /// <see cref="long"/> in the backing bits array, and the result is not /// internally cached! /// </summary> public int Cardinality() { return (int)BitUtil.Pop_Array(bits, 0, bits.Length); } public bool Get(int index) { Debug.Assert(index >= 0 && index < numBits, "index=" + index + ", numBits=" + numBits); int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } public void Set(int index) { Debug.Assert(index >= 0 && index < numBits, "index=" + index + ", numBits=" + numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] |= bitmask; } public bool GetAndSet(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bool val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } public void Clear(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } public bool GetAndClear(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bool val = (bits[wordNum] & bitmask) != 0; bits[wordNum] &= ~bitmask; return val; } /// <summary> /// Returns the index of the first set bit starting at the index specified. /// -1 is returned if there are no more set bits. /// </summary> public int NextSetBit(int index) { Debug.Assert(index >= 0 && index < numBits, "index=" + index + ", numBits=" + numBits); int i = index >> 6; int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word != 0) { return index + word.TrailingZeroCount(); } while (++i < numWords) { word = bits[i]; if (word != 0) { return (i << 6) + word.TrailingZeroCount(); } } return -1; } /// <summary> /// Returns the index of the last set bit before or on the index specified. /// -1 is returned if there are no more set bits. /// </summary> public int PrevSetBit(int index) { Debug.Assert(index >= 0 && index < numBits, "index=" + index + " numBits=" + numBits); int i = index >> 6; int subIndex = index & 0x3f; // index within the word long word = (bits[i] << (63 - subIndex)); // skip all the bits to the left of index if (word != 0) { return (i << 6) + subIndex - word.LeadingZeroCount(); // See LUCENE-3197 } while (--i >= 0) { word = bits[i]; if (word != 0) { return (i << 6) + 63 - word.LeadingZeroCount(); } } return -1; } /// <summary> /// Does in-place OR of the bits provided by the /// iterator. /// </summary> public void Or(DocIdSetIterator iter) { if (iter is OpenBitSetIterator && iter.DocID == -1) { OpenBitSetIterator obs = (OpenBitSetIterator)iter; Or(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.Advance(numBits); } else if (iter is FixedBitSetIterator && iter.DocID == -1) { FixedBitSetIterator fbs = (FixedBitSetIterator)iter; Or(fbs.bits, fbs.numWords); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): fbs.Advance(numBits); } else { int doc; while ((doc = iter.NextDoc()) < numBits) { Set(doc); } } } /// <summary> /// this = this OR other </summary> public void Or(FixedBitSet other) { Or(other.bits, other.numWords); } private void Or(long[] otherArr, int otherNumWords) { Debug.Assert(otherNumWords <= numWords, "numWords=" + numWords + ", otherNumWords=" + otherNumWords); long[] thisArr = this.bits; int pos = Math.Min(numWords, otherNumWords); while (--pos >= 0) { thisArr[pos] |= otherArr[pos]; } } /// <summary> /// this = this XOR other </summary> public void Xor(FixedBitSet other) { Debug.Assert(other.numWords <= numWords, "numWords=" + numWords + ", other.numWords=" + other.numWords); long[] thisBits = this.bits; long[] otherBits = other.bits; int pos = Math.Min(numWords, other.numWords); while (--pos >= 0) { thisBits[pos] ^= otherBits[pos]; } } /// <summary> /// Does in-place XOR of the bits provided by the iterator. </summary> public void Xor(DocIdSetIterator iter) { int doc; while ((doc = iter.NextDoc()) < numBits) { Flip(doc, doc + 1); } } /// <summary> /// Does in-place AND of the bits provided by the /// iterator. /// </summary> public void And(DocIdSetIterator iter) { if (iter is OpenBitSetIterator && iter.DocID == -1) { OpenBitSetIterator obs = (OpenBitSetIterator)iter; And(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.Advance(numBits); } else if (iter is FixedBitSetIterator && iter.DocID == -1) { FixedBitSetIterator fbs = (FixedBitSetIterator)iter; And(fbs.bits, fbs.numWords); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): fbs.Advance(numBits); } else { if (numBits == 0) { return; } int disiDoc, bitSetDoc = NextSetBit(0); while (bitSetDoc != -1 && (disiDoc = iter.Advance(bitSetDoc)) < numBits) { Clear(bitSetDoc, disiDoc); disiDoc++; bitSetDoc = (disiDoc < numBits) ? NextSetBit(disiDoc) : -1; } if (bitSetDoc != -1) { Clear(bitSetDoc, numBits); } } } /// <summary> /// Returns true if the sets have any elements in common </summary> public bool Intersects(FixedBitSet other) { int pos = Math.Min(numWords, other.numWords); while (--pos >= 0) { if ((bits[pos] & other.bits[pos]) != 0) { return true; } } return false; } /// <summary> /// this = this AND other </summary> public void And(FixedBitSet other) { And(other.bits, other.numWords); } private void And(long[] otherArr, int otherNumWords) { long[] thisArr = this.bits; int pos = Math.Min(this.numWords, otherNumWords); while (--pos >= 0) { thisArr[pos] &= otherArr[pos]; } if (this.numWords > otherNumWords) { Arrays.Fill(thisArr, otherNumWords, this.numWords, 0L); } } /// <summary> /// Does in-place AND NOT of the bits provided by the /// iterator. /// </summary> public void AndNot(DocIdSetIterator iter) { if (iter is OpenBitSetIterator && iter.DocID == -1) { OpenBitSetIterator obs = (OpenBitSetIterator)iter; AndNot(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.Advance(numBits); } else if (iter is FixedBitSetIterator && iter.DocID == -1) { FixedBitSetIterator fbs = (FixedBitSetIterator)iter; AndNot(fbs.bits, fbs.numWords); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): fbs.Advance(numBits); } else { int doc; while ((doc = iter.NextDoc()) < numBits) { Clear(doc); } } } /// <summary> /// this = this AND NOT other </summary> public void AndNot(FixedBitSet other) { AndNot(other.bits, other.bits.Length); } private void AndNot(long[] otherArr, int otherNumWords) { long[] thisArr = this.bits; int pos = Math.Min(this.numWords, otherNumWords); while (--pos >= 0) { thisArr[pos] &= ~otherArr[pos]; } } // NOTE: no .isEmpty() here because that's trappy (ie, // typically isEmpty is low cost, but this one wouldn't // be) /// <summary> /// Flips a range of bits /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to flip </param> public void Flip(int startIndex, int endIndex) { Debug.Assert(startIndex >= 0 && startIndex < numBits); Debug.Assert(endIndex >= 0 && endIndex <= numBits); if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex - 1) >> 6; /* ///* Grrr, java shifting wraps around so -1L>>>64 == -1 /// for that reason, make sure not to use endmask if the bits to flip will /// be zero in the last word (redefine endWord to be the last changed...) /// long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 /// long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 /// ** */ long startmask = -1L << startIndex; long endmask = (long)(unchecked((ulong)-1) >> -endIndex); //long endmask = -(int)((uint)1L >> -endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] ^= (startmask & endmask); return; } bits[startWord] ^= startmask; for (int i = startWord + 1; i < endWord; i++) { bits[i] = ~bits[i]; } bits[endWord] ^= endmask; } /// <summary> /// Sets a range of bits /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to set </param> public void Set(int startIndex, int endIndex) { Debug.Assert(startIndex >= 0 && startIndex < numBits); Debug.Assert(endIndex >= 0 && endIndex <= numBits); if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex - 1) >> 6; long startmask = -1L << startIndex; long endmask = (long)(unchecked((ulong)-1) >> -endIndex); //long endmask = -(int)((uint)1UL >> -endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] |= (startmask & endmask); return; } bits[startWord] |= startmask; Arrays.Fill(bits, startWord + 1, endWord, -1L); bits[endWord] |= endmask; } /// <summary> /// Clears a range of bits. /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to clear </param> public void Clear(int startIndex, int endIndex) { Debug.Assert(startIndex >= 0 && startIndex < numBits, "startIndex=" + startIndex + ", numBits=" + numBits); Debug.Assert(endIndex >= 0 && endIndex <= numBits, "endIndex=" + endIndex + ", numBits=" + numBits); if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex - 1) >> 6; long startmask = (-1L) << startIndex; // -1 << (startIndex mod 64) long endmask = (-1L) << endIndex; // -1 << (endIndex mod 64) if ((endIndex & 0x3f) == 0) { endmask = 0; } startmask = ~startmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; Arrays.Fill(bits, startWord + 1, endWord, 0L); bits[endWord] &= endmask; } public FixedBitSet Clone() { long[] bits = new long[this.bits.Length]; Array.Copy(this.bits, 0, bits, 0, bits.Length); return new FixedBitSet(bits, numBits); } /// <summary> /// Returns <c>true</c> if both sets have the same bits set </summary> public override bool Equals(object o) { if (this == o) { return true; } if (!(o is FixedBitSet)) { return false; } var other = (FixedBitSet)o; if (numBits != other.Length) { return false; } return Arrays.Equals(bits, other.bits); } public override int GetHashCode() { long h = 0; for (int i = numWords; --i >= 0; ) { h ^= bits[i]; h = (h << 1) | ((long)((ulong)h >> 63)); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int)((h >> 32) ^ h) + unchecked((int)0x98761234); } } }
using System; using System.Collections.Generic; using FluentSecurity.Policy; using FluentSecurity.Specification.Helpers; using FluentSecurity.Specification.TestData; using Moq; using NUnit.Framework; namespace FluentSecurity.Specification.Policy { [TestFixture] [Category("RequireRolePolicySpec")] public class When_passing_null_to_the_constructor_of_RequireRolePolicy { [Test] public void Should_throw_ArgumentNullException() { // Assert Assert.Throws<ArgumentNullException>(() => new RequireRolePolicy(null)); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_passing_an_empty_array_to_the_constructor_of_RequireRolePolicy { [Test] public void Should_throw_ArgumentException() { // Assert Assert.Throws<ArgumentException>(() => new RequireRolePolicy(new object[0])); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_passing_an_array_with_one_required_role_to_the_constructor_of_RequireRolePolicy { [Test] public void Should_not_throw() { // Assert Assert.DoesNotThrow(() => new RequireRolePolicy(new object[1])); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_getting_the_required_roles_for_a_RequireRolePolicy { [Test] public void Should_return_expected_roles() { // Arrange var expectedRoles = new List<object> { "Administrator", "Editor" }.ToArray(); var policy = new RequireRolePolicy(expectedRoles); // Act var rolesRequired = policy.RolesRequired; // Assert Assert.That(rolesRequired, Is.EqualTo(expectedRoles)); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_enforcing_security_for_a_RequireRolePolicy { [Test] public void Should_resolve_authentication_status_and_roles_exactly_once() { // Arrange var roles = new object[1]; var policy = new RequireRolePolicy(roles); var context = new Mock<ISecurityContext>(); context.Setup(x => x.CurrentUserIsAuthenticated()).Returns(true); context.Setup(x => x.CurrentUserRoles()).Returns(roles); // Act var result = policy.Enforce(context.Object); // Assert Assert.That(result.ViolationOccured, Is.False); context.Verify(x => x.CurrentUserIsAuthenticated(), Times.Exactly(1), "The authentication status should be resolved at most once."); context.Verify(x => x.CurrentUserRoles(), Times.Exactly(1), "The roles should be resolved at most once."); } [Test] public void Should_not_be_successful_when_isAuthenticated_is_false() { // Arrange var policy = new RequireRolePolicy(new object[1]); const bool authenticated = false; var context = TestDataFactory.CreateSecurityContext(authenticated); // Act var result = policy.Enforce(context); // Assert Assert.That(result.ViolationOccured, Is.True); Assert.That(result.Message, Is.EqualTo("Anonymous access denied")); } [Test] public void Should_not_be_successful_when_isAuthenticated_is_true_and_roles_are_null() { // Arrange var policy = new RequireRolePolicy(new object[1]); const bool authenticated = true; IEnumerable<object> roles = null; var context = TestDataFactory.CreateSecurityContext(authenticated, roles); // Act var result = policy.Enforce(context); // Assert Assert.That(result.ViolationOccured, Is.True); Assert.That(result.Message, Is.EqualTo("Access denied")); } [Test] public void Should_not_be_successful_when_isAuthenticated_is_true_and_roles_does_not_match() { // Arrange var policy = new RequireRolePolicy("Role1", "Role2"); const bool authenticated = true; var roles = new List<object> { "Role3", "Role4" }.ToArray(); var context = TestDataFactory.CreateSecurityContext(authenticated, roles); // Act var result = policy.Enforce(context); // Assert Assert.That(result.ViolationOccured, Is.True); Assert.That(result.Message, Is.EqualTo("Access requires one of the following roles: Role1 or Role2.")); } [Test] public void Should_be_successful_when_isAuthenticated_is_true_and_user_has_at_least_one_matching_role() { // Arrange var requiredRoles = new List<object> { UserRole.Writer, UserRole.Publisher }; var policy = new RequireRolePolicy(requiredRoles.ToArray()); const bool authenticated = true; var roles = new List<object> { UserRole.Writer }; var context = TestDataFactory.CreateSecurityContext(authenticated, roles.ToArray()); // Act var result = policy.Enforce(context); // Assert Assert.That(result.ViolationOccured, Is.False); } } [Category("RequireAllRolesPolicySpec")] public class When_doing_tostring_for_a_RequireRolePolicy { [Test] public void Should_return_name_and_role() { // Arrange var roles = new List<object> { "Administrator" }.ToArray(); var policy = new RequireRolePolicy(roles); // Act var result = policy.ToString(); // Assert Assert.That(result, Is.EqualTo("FluentSecurity.Policy.RequireRolePolicy (Administrator)")); } [Test] public void Should_return_name_and_roles() { // Arrange var roles = new List<object> { "Writer", "Editor", "Administrator" }.ToArray(); var policy = new RequireRolePolicy(roles); // Act var result = policy.ToString(); // Assert Assert.That(result, Is.EqualTo("FluentSecurity.Policy.RequireRolePolicy (Writer or Editor or Administrator)")); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_comparing_RequireRolePolicy { [Test] public void Should_be_equal() { var instance1 = new RequireRolePolicy("Editor"); var instance2 = new RequireRolePolicy("Editor"); Assert.That(instance1.Equals(instance2), Is.True); Assert.That(instance1 == instance2, Is.True); Assert.That(instance1 != instance2, Is.False); var instance3 = new RequireRolePolicy(UserRole.Writer); var instance4 = new RequireRolePolicy(UserRole.Writer); Assert.That(instance3.Equals(instance4), Is.True); Assert.That(instance3 == instance4, Is.True); Assert.That(instance3 != instance4, Is.False); } [Test] public void Should_not_be_equal_when_comparing_to_null() { var instance = new RequireRolePolicy("Editor"); Assert.That(instance.Equals(null), Is.False); } [Test] public void Should_not_be_equal_when_roles_differ() { var instance1 = new RequireRolePolicy("Editor"); var instance2 = new RequireRolePolicy("Writer"); Assert.That(instance1.Equals(instance2), Is.False); Assert.That(instance1 == instance2, Is.False); Assert.That(instance1 != instance2, Is.True); var instance3 = new RequireRolePolicy(UserRole.Publisher); var instance4 = new RequireRolePolicy(UserRole.Owner); Assert.That(instance3.Equals(instance4), Is.False); Assert.That(instance3 == instance4, Is.False); Assert.That(instance3 != instance4, Is.True); } [Test] public void Should_not_be_equal_when_roles_count_differ() { var instance1 = new RequireRolePolicy("Editor", "Writer"); var instance2 = new RequireRolePolicy("Writer"); Assert.That(instance1.Equals(instance2), Is.False); Assert.That(instance1 == instance2, Is.False); Assert.That(instance1 != instance2, Is.True); var instance3 = new RequireRolePolicy(UserRole.Owner, UserRole.Writer, UserRole.Publisher); var instance4 = new RequireRolePolicy(UserRole.Owner); Assert.That(instance3.Equals(instance4), Is.False); Assert.That(instance3 == instance4, Is.False); Assert.That(instance3 != instance4, Is.True); } } [TestFixture] [Category("RequireRolePolicySpec")] public class When_getting_the_hash_code_for_RequireRolePolicy { [Test] public void Should_be_the_same() { var instance1 = new RequireRolePolicy("Editor"); var instance2 = new RequireRolePolicy("Editor"); Assert.That(instance1.GetHashCode(), Is.EqualTo(instance2.GetHashCode())); var instance3 = new RequireRolePolicy(UserRole.Writer); var instance4 = new RequireRolePolicy(UserRole.Writer); Assert.That(instance3.GetHashCode(), Is.EqualTo(instance4.GetHashCode())); } [Test] public void Should_not_be_the_same_when_roles_differ() { var instance1 = new RequireRolePolicy("Editor"); var instance2 = new RequireRolePolicy("Writer"); Assert.That(instance1.GetHashCode(), Is.Not.EqualTo(instance2.GetHashCode())); var instance3 = new RequireRolePolicy(UserRole.Publisher); var instance4 = new RequireRolePolicy(UserRole.Owner); Assert.That(instance3.GetHashCode(), Is.Not.EqualTo(instance4.GetHashCode())); } [Test] public void Should_not_be_the_same_when_roles_count_differ() { var instance1 = new RequireRolePolicy("Editor", "Writer"); var instance2 = new RequireRolePolicy("Writer"); Assert.That(instance1.GetHashCode(), Is.Not.EqualTo(instance2.GetHashCode())); var instance3 = new RequireRolePolicy(UserRole.Owner, UserRole.Writer, UserRole.Publisher); var instance4 = new RequireRolePolicy(UserRole.Owner); Assert.That(instance3.GetHashCode(), Is.Not.EqualTo(instance4.GetHashCode())); } [Test] public void Should_not_be_the_same_when_types_differ() { var instance1 = new RequireAllRolesPolicy("Editor", "Writer"); var instance2 = new RequireRolePolicy("Editor", "Writer"); Assert.That(instance1.GetHashCode(), Is.Not.EqualTo(instance2.GetHashCode())); } } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------*/ #endregion namespace SemPlan.Spiral.Sparql { using SemPlan.Spiral.Core; using SemPlan.Spiral.Expressions; using System; using System.Collections; using System.Text.RegularExpressions; /// <summary> /// Represents a parser of the Sparql query syntax /// </summary> /// <remarks> /// $Id: QueryParser.cs,v 1.9 2006/02/10 22:10:12 ian Exp $ ///</remarks> public class QueryParser { private QueryTokenizer itsTokenEnum; private Hashtable itsPrefixes; private bool itsExplain; private State itsState; public QueryParser() { InitializeParserState(); } public bool Explain { get { return itsExplain; } set { itsExplain = value; itsState.Explain = Explain; } } private void InitializeParserState() { itsPrefixes = new Hashtable(); itsState = new PrologState(); } public Query Parse( String sparql ) { SparqlQuery query = new SparqlQuery(); ParseInto( query, sparql); return query; } public Query Parse( String sparql, string baseUri ) { SparqlQuery query = new SparqlQuery(); query.Base = baseUri; ParseInto( query, sparql); return query; } public void ParseInto( Query query, String sparql ) { InitializeParserState(); itsState.Explain = Explain; itsTokenEnum = TokenizeQuery( sparql ); while ( itsTokenEnum.MoveNext() ) { string token = (string)itsTokenEnum.TokenText; if (Explain) Console.WriteLine(" itsTokenEnum.TokenText is " + token + " (" + itsTokenEnum.Type + ")"); itsState = itsState.Handle(this, itsTokenEnum, query); itsState.Explain = Explain; } } public void RegisterPrefix( string prefix, string uri) { itsPrefixes[prefix] = uri; } public string GetPrefixUri( string prefix) { return (string)itsPrefixes[prefix]; } public bool HasPrefix( string prefix) { return itsPrefixes.Contains(prefix); } public BlankNode GetBlankNode( string label) { return new BlankNode(); } private QueryTokenizer TokenizeQuery( string sparql ) { return new QueryTokenizer( sparql ); } internal PatternTerm ParseTokenToMember( Query query ) { string token = (string)itsTokenEnum.TokenText; //if (Explain) Console.WriteLine("Parsing token to member: " + token + " (" + itsTokenEnum.Type + ")"); switch ( itsTokenEnum.Type ) { case QueryTokenizer.TokenType.Variable: return new Variable( token ); case QueryTokenizer.TokenType.QuotedIRIRef: return query.CreateUriRef( token ); case QueryTokenizer.TokenType.RDFLiteral: if ( token.StartsWith("\"") && token.EndsWith("\"") ) { return new PlainLiteral( token.Substring(1, token.Length - 2 ) ); } else if ( token.StartsWith("\"") && token.LastIndexOf("@") > token.LastIndexOf("\"") ) { return new PlainLiteral( token.Substring(1, token.LastIndexOf("\"") - 1 ), token.Substring( token.LastIndexOf("@") + 1) ); } else if ( token.StartsWith("\"") && token.LastIndexOf("^^<") > token.LastIndexOf("\"") && token.EndsWith(">")) { return new PlainLiteral( token.Substring(1, token.LastIndexOf("\"") - 1 ), token.Substring( token.LastIndexOf("^^<") + 3, token.Length - token.LastIndexOf("^^<") - 3) ); } else if ( token.StartsWith("'") && token.EndsWith("\'") ) { return new PlainLiteral( token.Substring(1, token.Length - 2 ) ); } else if ( token.StartsWith("'") && token.LastIndexOf("@") > token.LastIndexOf("\"") ) { return new PlainLiteral( token.Substring(1, token.LastIndexOf("\'") - 1 ), token.Substring( token.LastIndexOf("@") + 1) ); } else if ( token.StartsWith("'") && token.LastIndexOf("^^<") > token.LastIndexOf("\'") && token.EndsWith(">")) { return new PlainLiteral( token.Substring(1, token.LastIndexOf("\'") - 1 ), token.Substring( token.LastIndexOf("^^<") + 3, token.Length - token.LastIndexOf("^^<") - 3) ); } else { return new PlainLiteral( itsTokenEnum.TokenText ); } case QueryTokenizer.TokenType.QName: string prefix = token.Substring( 0, token.IndexOf( ":" ) + 1 ); string localPart = token.Substring( token.IndexOf( ":" ) + 1); if (! HasPrefix( prefix ) ) { throw new SparqlException("Error parsing prefix '" + prefix + "' at character " + itsTokenEnum.TokenAbsolutePosition + ". This prefix has not been declared."); } return query.CreateUriRef( GetPrefixUri( prefix ) + localPart ); case QueryTokenizer.TokenType.PrefixName: return query.CreateUriRef( GetPrefixUri( token )); case QueryTokenizer.TokenType.NumericInteger: return new TypedLiteral( itsTokenEnum.TokenText, "http://www.w3.org/2001/XMLSchema#integer" ); case QueryTokenizer.TokenType.NumericDecimal: return new TypedLiteral( itsTokenEnum.TokenText, "http://www.w3.org/2001/XMLSchema#decimal" ); case QueryTokenizer.TokenType.NumericDouble: return new TypedLiteral( itsTokenEnum.TokenText, "http://www.w3.org/2001/XMLSchema#double" ); case QueryTokenizer.TokenType.Boolean: return new TypedLiteral( itsTokenEnum.TokenText, "http://www.w3.org/2001/XMLSchema#boolean" ); case QueryTokenizer.TokenType.KeywordA: return new UriRef( "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" ); case QueryTokenizer.TokenType.BlankNode: return GetBlankNode( itsTokenEnum.TokenText ); } throw new SparqlException("Unknown token '" + token + " (" + itsTokenEnum.Type + ")" + "' found at character " + itsTokenEnum.TokenAbsolutePosition); } internal Expression ParseExpression( ) { Expression expression = null; int groupDepth = 0; do { switch ( itsTokenEnum.Type ) { case QueryTokenizer.TokenType.Variable: expression = new VariableExpression( new Variable( itsTokenEnum.TokenText ) ); if ( groupDepth <= 0) return expression; break; case QueryTokenizer.TokenType.BeginGroup: ++groupDepth; break; case QueryTokenizer.TokenType.EndGroup: --groupDepth; if ( groupDepth <= 0) return expression; break; } } while ( itsTokenEnum.MoveNext() ); return expression; } private class EndOfQueryState : State { public override bool IsEnd { get { return true; } } public override State Handle(QueryParser parser, QueryTokenizer tokenizer, Query query) { return this; } } } }
/* * Copyright (c) 2007-2008, the libsecondlife development team * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Threading; using libsecondlife.Packets; namespace libsecondlife { /// <summary> /// Registers, unregisters, and fires events generated by incoming packets /// </summary> public class PacketEventDictionary { /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing packet callbacks /// </summary> private struct PacketCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public NetworkManager.PacketCallback Callback; /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>The packet that needs to be processed</summary> public Packet Packet; } /// <summary>Reference to the SecondLife client</summary> public SecondLife Client; private Dictionary<PacketType, NetworkManager.PacketCallback> _EventTable = new Dictionary<PacketType,NetworkManager.PacketCallback>(); private WaitCallback _ThreadPoolCallback; /// <summary> /// Default constructor /// </summary> /// <param name="client"></param> public PacketEventDictionary(SecondLife client) { Client = client; _ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate); } /// <summary> /// Register an event handler /// </summary> /// <remarks>Use PacketType.Default to fire this event on every /// incoming packet</remarks> /// <param name="packetType">Packet type to register the handler for</param> /// <param name="eventHandler">Callback to be fired</param> public void RegisterEvent(PacketType packetType, NetworkManager.PacketCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(packetType)) _EventTable[packetType] += eventHandler; else _EventTable[packetType] = eventHandler; } } /// <summary> /// Unregister an event handler /// </summary> /// <param name="packetType">Packet type to unregister the handler for</param> /// <param name="eventHandler">Callback to be unregistered</param> public void UnregisterEvent(PacketType packetType, NetworkManager.PacketCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(packetType) && _EventTable[packetType] != null) _EventTable[packetType] -= eventHandler; } } /// <summary> /// Fire the events registered for this packet type synchronously /// </summary> /// <param name="packetType">Incoming packet type</param> /// <param name="packet">Incoming packet</param> /// <param name="simulator">Simulator this packet was received from</param> internal void RaiseEvent(PacketType packetType, Packet packet, Simulator simulator) { NetworkManager.PacketCallback callback; if (_EventTable.TryGetValue(packetType, out callback)) { try { callback(packet, simulator); } catch (Exception ex) { Logger.Log("Packet Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } else if (packetType != PacketType.Default && packetType != PacketType.PacketAck) { Logger.DebugLog("No handler registered for packet event " + packetType, Client); } } /// <summary> /// Fire the events registered for this packet type asynchronously /// </summary> /// <param name="packetType">Incoming packet type</param> /// <param name="packet">Incoming packet</param> /// <param name="simulator">Simulator this packet was received from</param> internal void BeginRaiseEvent(PacketType packetType, Packet packet, Simulator simulator) { NetworkManager.PacketCallback callback; if (_EventTable.TryGetValue(packetType, out callback)) { if (callback != null) { PacketCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.Packet = packet; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); return; } } if (packetType != PacketType.Default && packetType != PacketType.PacketAck) { Logger.DebugLog("No handler registered for packet event " + packetType, Client); } } private void ThreadPoolDelegate(Object state) { PacketCallbackWrapper wrapper = (PacketCallbackWrapper)state; try { wrapper.Callback(wrapper.Packet, wrapper.Simulator); } catch (Exception ex) { Logger.Log("Async Packet Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } /// <summary> /// Registers, unregisters, and fires events generated by the Capabilities /// event queue /// </summary> public class CapsEventDictionary { /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing CAPS callbacks /// </summary> private struct CapsCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public Caps.EventQueueCallback Callback; /// <summary>Name of the CAPS event</summary> public string CapsEvent; /// <summary>Decoded body of the CAPS event</summary> public StructuredData.LLSD Body; /// <summary>Reference to the simulator that generated this event</summary> public Simulator Simulator; } /// <summary>Reference to the SecondLife client</summary> public SecondLife Client; private Dictionary<string, Caps.EventQueueCallback> _EventTable = new Dictionary<string, Caps.EventQueueCallback>(); private WaitCallback _ThreadPoolCallback; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the SecondLife client</param> public CapsEventDictionary(SecondLife client) { Client = client; _ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate); } /// <summary> /// Register an event handler /// </summary> /// <remarks>Use String.Empty to fire this event on every CAPS event</remarks> /// <param name="capsEvent">Capability event name to register the /// handler for</param> /// <param name="eventHandler">Callback to fire</param> public void RegisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent)) _EventTable[capsEvent] += eventHandler; else _EventTable[capsEvent] = eventHandler; } } /// <summary> /// /// </summary> /// <param name="capsEvent">Capability event name unregister the /// handler for</param> /// <param name="eventHandler">Callback to unregister</param> public void UnregisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent) && _EventTable[capsEvent] != null) _EventTable[capsEvent] -= eventHandler; } } /// <summary> /// Fire the events registered for this event type synchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="body">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void RaiseEvent(string capsEvent, StructuredData.LLSD body, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(capsEvent, out callback)) { if (callback != null) { try { callback(capsEvent, body, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } // Generic parser next if (body.Type == StructuredData.LLSDType.Map) { StructuredData.LLSDMap map = (StructuredData.LLSDMap)body; Packet packet = Packet.BuildPacket(capsEvent, map); if (packet != null) { NetworkManager.IncomingPacket incomingPacket; incomingPacket.Simulator = simulator; incomingPacket.Packet = packet; Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Client); Client.Network.PacketInbox.Enqueue(incomingPacket); specialHandler = true; } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { try { callback(capsEvent, body, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } /// <summary> /// Fire the events registered for this event type asynchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="body">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void BeginRaiseEvent(string capsEvent, StructuredData.LLSD body, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(String.Empty, out callback)) { if (callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Body = body; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); } } // Generic parser next, don't generic parse events we've manually registered for if (body.Type == StructuredData.LLSDType.Map && !_EventTable.ContainsKey(capsEvent)) { StructuredData.LLSDMap map = (StructuredData.LLSDMap)body; Packet packet = Packet.BuildPacket(capsEvent, map); if (packet != null) { NetworkManager.IncomingPacket incomingPacket; incomingPacket.Simulator = simulator; incomingPacket.Packet = packet; Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Client); Client.Network.PacketInbox.Enqueue(incomingPacket); specialHandler = true; } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Body = body; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } private void ThreadPoolDelegate(Object state) { CapsCallbackWrapper wrapper = (CapsCallbackWrapper)state; try { wrapper.Callback(wrapper.CapsEvent, wrapper.Body, wrapper.Simulator); } catch (Exception ex) { Logger.Log("Async CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WebApiBook.ProcessingArchitecture.ProcessesApi.v2.Areas.HelpPage.Models; namespace WebApiBook.ProcessingArchitecture.ProcessesApi.v2.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates.Asn1; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed class OpenSslX509ChainProcessor : IChainPal { // Constructed (0x20) | Sequence (0x10) => 0x30. private const uint ConstructedSequenceTagId = 0x30; public void Dispose() { } public bool? Verify(X509VerificationFlags flags, out Exception exception) { exception = null; return ChainVerifier.Verify(ChainElements, flags); } public X509ChainElement[] ChainElements { get; private set; } public X509ChainStatus[] ChainStatus { get; private set; } public SafeX509ChainHandle SafeHandle { get { return null; } } public static IChainPal BuildChain( X509Certificate2 leaf, HashSet<X509Certificate2> candidates, HashSet<X509Certificate2> systemTrusted, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, ref TimeSpan remainingDownloadTime) { X509ChainElement[] elements; List<X509ChainStatus> overallStatus = new List<X509ChainStatus>(); WorkingChain workingChain = new WorkingChain(); Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback; // An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to // Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes. // // (If you need to think of it as an X509Store, it's a volatile memory store) using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate()) using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate()) using (SafeX509StackHandle extraCerts = Interop.Crypto.NewX509Stack()) { Interop.Crypto.CheckValidOpenSslHandle(store); Interop.Crypto.CheckValidOpenSslHandle(storeCtx); Interop.Crypto.CheckValidOpenSslHandle(extraCerts); bool lookupCrl = revocationMode != X509RevocationMode.NoCheck; foreach (X509Certificate2 cert in candidates) { OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal; using (SafeX509Handle handle = Interop.Crypto.X509UpRef(pal.SafeHandle)) { if (!Interop.Crypto.PushX509StackField(extraCerts, handle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Ownership was transferred to the cert stack. handle.SetHandleAsInvalid(); } if (lookupCrl) { CrlCache.AddCrlForCertificate( cert, store, revocationMode, verificationTime, ref remainingDownloadTime); // If we only wanted the end-entity certificate CRL then don't look up // any more of them. lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly; } } if (revocationMode != X509RevocationMode.NoCheck) { if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } foreach (X509Certificate2 trustedCert in systemTrusted) { OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)trustedCert.Pal; if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle; if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle, extraCerts)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback); Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime); int verify = Interop.Crypto.X509VerifyCert(storeCtx); if (verify < 0) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the // chain is just fine (unless it returned a negative code for an exception) Debug.Assert(verify == 1, "verify == 1"); using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx)) { int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack); elements = new X509ChainElement[chainSize]; int maybeRootDepth = chainSize - 1; // The leaf cert is 0, up to (maybe) the root at chainSize - 1 for (int i = 0; i < chainSize; i++) { List<X509ChainStatus> status = new List<X509ChainStatus>(); List<Interop.Crypto.X509VerifyStatusCode> elementErrors = i < workingChain.Errors.Count ? workingChain.Errors[i] : null; if (elementErrors != null) { AddElementStatus(elementErrors, status, overallStatus); } IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i); if (elementCertPtr == IntPtr.Zero) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Duplicate the certificate handle X509Certificate2 elementCert = new X509Certificate2(elementCertPtr); elements[i] = new X509ChainElement(elementCert, status.ToArray(), ""); } } } GC.KeepAlive(workingCallback); if ((certificatePolicy != null && certificatePolicy.Count > 0) || (applicationPolicy != null && applicationPolicy.Count > 0)) { List<X509Certificate2> certsToRead = new List<X509Certificate2>(); foreach (X509ChainElement element in elements) { certsToRead.Add(element.Certificate); } CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead); bool failsPolicyChecks = false; if (certificatePolicy != null) { if (!policyChain.MatchesCertificatePolicies(certificatePolicy)) { failsPolicyChecks = true; } } if (applicationPolicy != null) { if (!policyChain.MatchesApplicationPolicies(applicationPolicy)) { failsPolicyChecks = true; } } if (failsPolicyChecks) { X509ChainElement leafElement = elements[0]; X509ChainStatus chainStatus = new X509ChainStatus { Status = X509ChainStatusFlags.NotValidForUsage, StatusInformation = SR.Chain_NoPolicyMatch, }; var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1); elementStatus.AddRange(leafElement.ChainElementStatus); AddUniqueStatus(elementStatus, ref chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); elements[0] = new X509ChainElement( leafElement.Certificate, elementStatus.ToArray(), leafElement.Information); } } return new OpenSslX509ChainProcessor { ChainStatus = overallStatus.ToArray(), ChainElements = elements, }; } private static void AddElementStatus( List<Interop.Crypto.X509VerifyStatusCode> errorCodes, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { foreach (var errorCode in errorCodes) { AddElementStatus(errorCode, elementStatus, overallStatus); } } private static void AddElementStatus( Interop.Crypto.X509VerifyStatusCode errorCode, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode); Debug.Assert( (statusFlag & (statusFlag - 1)) == 0, "Status flag has more than one bit set", "More than one bit is set in status '{0}' for error code '{1}'", statusFlag, errorCode); foreach (X509ChainStatus currentStatus in elementStatus) { if ((currentStatus.Status & statusFlag) != 0) { return; } } X509ChainStatus chainStatus = new X509ChainStatus { Status = statusFlag, StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode), }; elementStatus.Add(chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); } private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status) { X509ChainStatusFlags statusCode = status.Status; for (int i = 0; i < list.Count; i++) { if (list[i].Status == statusCode) { return; } } list.Add(status); } private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code) { switch (code) { case Interop.Crypto.X509VerifyStatusCode.X509_V_OK: return X509ChainStatusFlags.NoError; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: return X509ChainStatusFlags.NotTimeValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED: return X509ChainStatusFlags.Revoked; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE: return X509ChainStatusFlags.NotSignatureValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: return X509ChainStatusFlags.UntrustedRoot; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED: return X509ChainStatusFlags.OfflineRevocation; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: return X509ChainStatusFlags.RevocationStatusUnknown; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION: return X509ChainStatusFlags.InvalidExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: return X509ChainStatusFlags.PartialChain; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE: return X509ChainStatusFlags.NotValidForUsage; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: return X509ChainStatusFlags.InvalidBasicConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY: return X509ChainStatusFlags.InvalidPolicyConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED: return X509ChainStatusFlags.ExplicitDistrust; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: return X509ChainStatusFlags.HasNotSupportedCriticalExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG: throw new CryptographicException(); case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM: throw new OutOfMemoryException(); default: Debug.Fail("Unrecognized X509VerifyStatusCode:" + code); throw new CryptographicException(); } } internal static HashSet<X509Certificate2> FindCandidates( X509Certificate2 leaf, X509Certificate2Collection extraStore, HashSet<X509Certificate2> downloaded, HashSet<X509Certificate2> systemTrusted, ref TimeSpan remainingDownloadTime) { var candidates = new HashSet<X509Certificate2>(); var toProcess = new Queue<X509Certificate2>(); toProcess.Enqueue(leaf); using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine)) using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser)) using (var userMyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { systemRootStore.Open(OpenFlags.ReadOnly); systemIntermediateStore.Open(OpenFlags.ReadOnly); userRootStore.Open(OpenFlags.ReadOnly); userIntermediateStore.Open(OpenFlags.ReadOnly); userMyStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection systemRootCerts = systemRootStore.Certificates; X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates; X509Certificate2Collection userRootCerts = userRootStore.Certificates; X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates; X509Certificate2Collection userMyCerts = userMyStore.Certificates; // fill the system trusted collection foreach (X509Certificate2 userRootCert in userRootCerts) { if (!systemTrusted.Add(userRootCert)) { // If we have already (effectively) added another instance of this certificate, // then this one provides no value. A Disposed cert won't harm the matching logic. userRootCert.Dispose(); } } foreach (X509Certificate2 systemRootCert in systemRootCerts) { if (!systemTrusted.Add(systemRootCert)) { // If we have already (effectively) added another instance of this certificate, // (for example, because another copy of it was in the user store) // then this one provides no value. A Disposed cert won't harm the matching logic. systemRootCert.Dispose(); } } X509Certificate2Collection[] storesToCheck = { extraStore, userMyCerts, userIntermediateCerts, systemIntermediateCerts, userRootCerts, systemRootCerts, }; while (toProcess.Count > 0) { X509Certificate2 current = toProcess.Dequeue(); candidates.Add(current); HashSet<X509Certificate2> results = FindIssuer( current, storesToCheck, downloaded, ref remainingDownloadTime); if (results != null) { foreach (X509Certificate2 result in results) { if (!candidates.Contains(result)) { toProcess.Enqueue(result); } } } } // Avoid sending unused certs into the finalizer queue by doing only a ref check var candidatesByReference = new HashSet<X509Certificate2>( candidates, ReferenceEqualityComparer<X509Certificate2>.Instance); // Certificates come from 6 sources: // 1) extraStore. // These are cert objects that are provided by the user, we shouldn't dispose them. // 2) the machine root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 3) the user root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 4) the machine intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. // 5) the user intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. // 6) the user my store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. DisposeUnreferenced(candidatesByReference, systemIntermediateCerts); DisposeUnreferenced(candidatesByReference, userIntermediateCerts); DisposeUnreferenced(candidatesByReference, userMyCerts); } return candidates; } private static void DisposeUnreferenced( ISet<X509Certificate2> referencedSet, X509Certificate2Collection storeCerts) { foreach (X509Certificate2 cert in storeCerts) { if (!referencedSet.Contains(cert)) { cert.Dispose(); } } } private static HashSet<X509Certificate2> FindIssuer( X509Certificate2 cert, X509Certificate2Collection[] stores, HashSet<X509Certificate2> downloadedCerts, ref TimeSpan remainingDownloadTime) { if (IsSelfSigned(cert)) { // It's a root cert, we won't make any progress. return null; } SafeX509Handle certHandle = ((OpenSslX509CertificateReader)cert.Pal).SafeHandle; foreach (X509Certificate2Collection store in stores) { HashSet<X509Certificate2> fromStore = null; foreach (X509Certificate2 candidate in store) { var certPal = (OpenSslX509CertificateReader)candidate.Pal; if (certPal == null) { continue; } SafeX509Handle candidateHandle = certPal.SafeHandle; int issuerError = Interop.Crypto.X509CheckIssued(candidateHandle, certHandle); if (issuerError == 0) { if (fromStore == null) { fromStore = new HashSet<X509Certificate2>(); } fromStore.Add(candidate); } } if (fromStore != null) { return fromStore; } } byte[] authorityInformationAccess = null; foreach (X509Extension extension in cert.Extensions) { if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.AuthorityInformationAccess)) { // If there's an Authority Information Access extension, it might be used for // looking up additional certificates for the chain. authorityInformationAccess = extension.RawData; break; } } if (authorityInformationAccess != null) { X509Certificate2 downloaded = DownloadCertificate( authorityInformationAccess, ref remainingDownloadTime); if (downloaded != null) { downloadedCerts.Add(downloaded); return new HashSet<X509Certificate2>() { downloaded }; } } return null; } private static bool IsSelfSigned(X509Certificate2 cert) { return StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer); } private static X509Certificate2 DownloadCertificate( byte[] authorityInformationAccess, ref TimeSpan remainingDownloadTime) { // Don't do any work if we're over limit. if (remainingDownloadTime <= TimeSpan.Zero) { return null; } string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers); if (uri == null) { return null; } return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime); } internal static string FindHttpAiaRecord(byte[] authorityInformationAccess, string recordTypeOid) { AsnReader reader = new AsnReader(authorityInformationAccess, AsnEncodingRules.DER); AsnReader sequenceReader = reader.ReadSequence(); reader.ThrowIfNotEmpty(); while (sequenceReader.HasData) { AccessDescriptionAsn.Decode(sequenceReader, out AccessDescriptionAsn description); if (StringComparer.Ordinal.Equals(description.AccessMethod, recordTypeOid)) { GeneralNameAsn name = description.AccessLocation; if (name.Uri != null && Uri.TryCreate(name.Uri, UriKind.Absolute, out Uri uri) && uri.Scheme == "http") { return name.Uri; } } } return null; } private class WorkingChain { internal readonly List<List<Interop.Crypto.X509VerifyStatusCode>> Errors = new List<List<Interop.Crypto.X509VerifyStatusCode>>(); internal int VerifyCallback(int ok, IntPtr ctx) { if (ok != 0) { return ok; } try { using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false)) { Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx); int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx); // We don't report "OK" as an error. // For compatibility with Windows / .NET Framework, do not report X509_V_CRL_NOT_YET_VALID. if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK && errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID) { while (Errors.Count <= errorDepth) { Errors.Add(null); } if (Errors[errorDepth] == null) { Errors[errorDepth] = new List<Interop.Crypto.X509VerifyStatusCode>(); } Errors[errorDepth].Add(errorCode); } } return 1; } catch { return -1; } } } } }
// 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.Extensions; namespace osu.Framework.Tests.Lists { [TestFixture] public class TestArrayExtensions { [Test] public void TestNullToJagged() { int[][] result = null; Assert.DoesNotThrow(() => result = ((int[,])null).ToJagged()); Assert.AreEqual(null, result); } [Test] public void TestNullToRectangular() { int[,] result = null; Assert.DoesNotThrow(() => result = ((int[][])null).ToRectangular()); Assert.AreEqual(null, result); } [Test] public void TestEmptyRectangularToJagged() { int[][] result = null; Assert.DoesNotThrow(() => result = new int[0, 0].ToJagged()); Assert.AreEqual(0, result.Length); } [Test] public void TestEmptyJaggedToRectangular() { int[,] result = null; Assert.DoesNotThrow(() => result = new int[0][].ToRectangular()); Assert.AreEqual(0, result.Length); } [Test] public void TestRectangularColumnToJagged() { int[][] result = null; Assert.DoesNotThrow(() => result = new int[1, 10].ToJagged()); Assert.AreEqual(1, result.Length); Assert.AreEqual(10, result[0].Length); } [Test] public void TestJaggedColumnToRectangular() { var jagged = new int[10][]; int[,] result = null; Assert.DoesNotThrow(() => result = jagged.ToRectangular()); Assert.AreEqual(10, result.GetLength(0)); } [Test] public void TestRectangularRowToJagged() { int[][] result = null; Assert.DoesNotThrow(() => result = new int[10, 0].ToJagged()); Assert.AreEqual(10, result.Length); for (int i = 0; i < 10; i++) Assert.AreEqual(0, result[i].Length); } [Test] public void TestJaggedRowToRectangular() { var jagged = new int[1][]; jagged[0] = new int[10]; int[,] result = null; Assert.DoesNotThrow(() => result = jagged.ToRectangular()); Assert.AreEqual(10, result.GetLength(1)); Assert.AreEqual(1, result.GetLength(0)); } [Test] public void TestSquareRectangularToJagged() { int[][] result = null; Assert.DoesNotThrow(() => result = new int[10, 10].ToJagged()); Assert.AreEqual(10, result.Length); for (int i = 0; i < 10; i++) Assert.AreEqual(10, result[i].Length); } [Test] public void TestSquareJaggedToRectangular() { var jagged = new int[10][]; for (int i = 0; i < 10; i++) jagged[i] = new int[10]; int[,] result = null; Assert.DoesNotThrow(() => result = jagged.ToRectangular()); Assert.AreEqual(10, result.GetLength(0)); Assert.AreEqual(10, result.GetLength(1)); } [Test] public void TestNonSquareJaggedToRectangular() { var jagged = new int[10][]; for (int i = 0; i < 10; i++) jagged[i] = new int[i]; int[,] result = null; Assert.DoesNotThrow(() => result = jagged.ToRectangular()); Assert.AreEqual(10, result.GetLength(0)); Assert.AreEqual(9, result.GetLength(1)); } [Test] public void TestNonSquareJaggedWithNullRowsToRectangular() { var jagged = new int[10][]; for (int i = 1; i < 10; i += 2) { if (i % 2 == 1) jagged[i] = new int[i]; } int[,] result = null; Assert.DoesNotThrow(() => result = jagged.ToRectangular()); Assert.AreEqual(10, result.GetLength(0)); Assert.AreEqual(9, result.GetLength(1)); for (int i = 0; i < 10; i++) Assert.AreEqual(0, result[i, 0]); } [Test] public void TestInvertRectangular() { var original = new int?[,] { { 1, 2, null }, { null, 3, 4 }, { 5, 6, null } }; var result = original.Invert(); Assert.AreEqual(1, result[0, 0]); Assert.AreEqual(2, result[1, 0]); Assert.AreEqual(null, result[2, 0]); Assert.AreEqual(null, result[0, 1]); Assert.AreEqual(3, result[1, 1]); Assert.AreEqual(4, result[2, 1]); Assert.AreEqual(5, result[0, 2]); Assert.AreEqual(6, result[1, 2]); Assert.AreEqual(null, result[2, 2]); } [Test] public void TestInvertJagged() { // 4x5 array var original = new[] { new int?[] { 1, 2, null }, new int?[] { 3, 4 }, null, new int?[] { null, 5, 6, 7, 8} }; var result = original.Invert(); // Ensure 5x4 array Assert.AreEqual(5, result.Length); Assert.AreEqual(4, result.Max(r => r.Length)); // Column 1 Assert.AreEqual(1, result[0][0]); Assert.AreEqual(2, result[1][0]); Assert.AreEqual(null, result[2][0]); Assert.AreEqual(null, result[3][0]); Assert.AreEqual(null, result[4][0]); // Column 2 Assert.AreEqual(3, result[0][1]); Assert.AreEqual(4, result[1][1]); Assert.AreEqual(null, result[2][1]); Assert.AreEqual(null, result[3][1]); Assert.AreEqual(null, result[4][1]); // Column 3 Assert.AreEqual(null, result[0][2]); Assert.AreEqual(null, result[1][2]); Assert.AreEqual(null, result[2][2]); Assert.AreEqual(null, result[3][2]); Assert.AreEqual(null, result[4][2]); // Column 4 Assert.AreEqual(null, result[0][3]); Assert.AreEqual(5, result[1][3]); Assert.AreEqual(6, result[2][3]); Assert.AreEqual(7, result[3][3]); Assert.AreEqual(8, result[4][3]); } } }
/*==========================================================================; * * This file is part of LATINO. See http://www.latinolib.org * * File: SvmMulticlassFast.cs * Desc: Multiclass SVM classifier based on SvmLightLib * Created: Jan-2011 * * Author: Miha Grcar * ***************************************************************************/ using System; using System.Collections.Generic; using System.Globalization; namespace Latino.Model { /* .----------------------------------------------------------------------- | | Class SvmMulticlassFast<LblT> | '----------------------------------------------------------------------- */ public class SvmMulticlassClassifier<LblT> : IModel<LblT, SparseVector<double>>, IDisposable { private Dictionary<LblT, int> mLblToId // 1-based = new Dictionary<LblT, int>(); private ArrayList<LblT> mIdxToLbl // 0-based = new ArrayList<LblT>(); private IEqualityComparer<LblT> mLblCmp = null; private int mModelId = -1; private double mC = 5000; private double mEps = 0.1; public SvmMulticlassClassifier() { } public SvmMulticlassClassifier(BinarySerializer reader) { Load(reader); // throws ArgumentNullException, serialization-related exceptions } public IEqualityComparer<LblT> LabelEqualityComparer { get { return mLblCmp; } set { mLblCmp = value; } } public double C { get { return mC; } set { Utils.ThrowException(value <= 0 ? new ArgumentOutOfRangeException("C") : null); mC = value; } } public double Eps { get { return mEps; } set { Utils.ThrowException(value <= 0 ? new ArgumentOutOfRangeException("Eps") : null); mEps = value; } } // *** IModel<LblT, SparseVector<double>> interface implementation *** public Type RequiredExampleType { get { return typeof(SparseVector<double>); } } public bool IsTrained { get { return mModelId != -1; } } public void Train(ILabeledExampleCollection<LblT, SparseVector<double>> dataset) { Utils.ThrowException(dataset == null ? new ArgumentNullException("dataset") : null); Utils.ThrowException(dataset.Count == 0 ? new ArgumentValueException("dataset") : null); Dispose(); int[] trainSet = new int[dataset.Count]; int[] labels = new int[dataset.Count]; int j = 0; foreach (LabeledExample<LblT, SparseVector<double>> lblEx in dataset) { SparseVector<double> vec = lblEx.Example; int[] idx = new int[vec.Count]; float[] val = new float[vec.Count]; for (int i = 0; i < vec.Count; i++) { idx[i] = vec.InnerIdx[i] + 1; // *** indices are 1-based in SvmLightLib val[i] = (float)vec.InnerDat[i]; // *** loss of precision (double -> float) } int lbl; if (!mLblToId.TryGetValue(lblEx.Label, out lbl)) { mLblToId.Add(lblEx.Label, lbl = mLblToId.Count + 1); // *** labels start with 1 in SvmLightLib mIdxToLbl.Add(lblEx.Label); } trainSet[j++] = SvmLightLib.NewFeatureVector(idx.Length, idx, val, lbl); } mModelId = SvmLightLib.TrainMulticlassModel(string.Format("-c {0} -e {1}", mC.ToString(CultureInfo.InvariantCulture), mEps.ToString(CultureInfo.InvariantCulture)), trainSet.Length, trainSet); // delete training vectors foreach (int vecIdx in trainSet) { SvmLightLib.DeleteFeatureVector(vecIdx); } } void IModel<LblT>.Train(ILabeledExampleCollection<LblT> dataset) { Utils.ThrowException(dataset == null ? new ArgumentNullException("dataset") : null); Utils.ThrowException(!(dataset is ILabeledExampleCollection<LblT, SparseVector<double>>) ? new ArgumentTypeException("dataset") : null); Train((ILabeledExampleCollection<LblT, SparseVector<double>>)dataset); // throws ArgumentValueException } public Prediction<LblT> Predict(SparseVector<double> example) { Utils.ThrowException(mModelId == -1 ? new InvalidOperationException() : null); Utils.ThrowException(example == null ? new ArgumentNullException("example") : null); Prediction<LblT> result = new Prediction<LblT>(); int[] idx = new int[example.Count]; float[] val = new float[example.Count]; for (int i = 0; i < example.Count; i++) { idx[i] = example.InnerIdx[i] + 1; // *** indices are 1-based in SvmLightLib val[i] = (float)example.InnerDat[i]; // *** loss of precision (double -> float) } int vecId = SvmLightLib.NewFeatureVector(idx.Length, idx, val, 0); SvmLightLib.MulticlassClassify(mModelId, 1, new int[] { vecId }); int n = SvmLightLib.GetFeatureVectorClassifScoreCount(vecId); for (int i = 0; i < n; i++) { double score = SvmLightLib.GetFeatureVectorClassifScore(vecId, i); LblT lbl = mIdxToLbl[i]; result.Inner.Add(new KeyDat<double, LblT>(score, lbl)); } result.Inner.Sort(DescSort<KeyDat<double, LblT>>.Instance); result.Trim(); SvmLightLib.DeleteFeatureVector(vecId); // delete feature vector return result; } Prediction<LblT> IModel<LblT>.Predict(object example) { Utils.ThrowException(example == null ? new ArgumentNullException("example") : null); Utils.ThrowException(!(example is SparseVector<double>) ? new ArgumentTypeException("example") : null); return Predict((SparseVector<double>)example); // throws InvalidOperationException } // *** IDisposable interface implementation *** public void Dispose() { if (mModelId != -1) { SvmLightLib.DeleteMulticlassModel(mModelId); mLblToId.Clear(); mIdxToLbl.Clear(); mModelId = -1; } } // *** ISerializable interface implementation *** public void Save(BinarySerializer writer) { Utils.ThrowException(writer == null ? new ArgumentNullException("writer") : null); // the following statements throw serialization-related exceptions writer.WriteDouble(mC); writer.WriteDouble(mEps); mIdxToLbl.Save(writer); writer.WriteObject(mLblCmp); writer.WriteBool(mModelId != -1); if (mModelId != -1) { SvmLightLib.WriteByteCallback wb = delegate(byte b) { writer.WriteByte(b); }; SvmLightLib.SaveMulticlassModelBinCallback(mModelId, wb); GC.KeepAlive(wb); } } public void Load(BinarySerializer reader) { Utils.ThrowException(reader == null ? new ArgumentNullException("reader") : null); Dispose(); // the following statements throw serialization-related exceptions mC = reader.ReadDouble(); mEps = reader.ReadDouble(); mIdxToLbl.Load(reader); for (int i = 0; i < mIdxToLbl.Count; i++) { mLblToId.Add(mIdxToLbl[i], i + 1); } mLblCmp = reader.ReadObject<IEqualityComparer<LblT>>(); if (reader.ReadBool()) { SvmLightLib.ReadByteCallback rb = delegate() { return reader.ReadByte(); }; mModelId = SvmLightLib.LoadMulticlassModelBinCallback(rb); GC.KeepAlive(rb); } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Sundry Debtor Fees /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SDFC : EduHubEntity { #region Navigation Property Cache private GL Cache_GLCODE_GL; private KGST Cache_GST_TYPE_KGST; private KGLSUB Cache_SUBPROGRAM_KGLSUB; private KGLINIT Cache_INITIATIVE_KGLINIT; #endregion #region Foreign Navigation Properties private IReadOnlyList<DRF> Cache_SDFCKEY_DRF_FEE_CODE; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Prime Key /// [Uppercase Alphanumeric (10)] /// </summary> public string SDFCKEY { get; internal set; } /// <summary> /// Fees table title /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION { get; internal set; } /// <summary> /// Group for reports only /// [Alphanumeric (10)] /// </summary> public string SDGROUP { get; internal set; } /// <summary> /// Fees tables to be used for auto transactions? /// [Alphanumeric (1)] /// </summary> public string STATEMENT { get; internal set; } /// <summary> /// Method of fees calculation /// [Alphanumeric (1)] /// </summary> public string METHOD { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public decimal? AMOUNT { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public decimal? GROSS_AMOUNT { get; internal set; } /// <summary> /// One GL key for each category /// [Uppercase Alphanumeric (10)] /// </summary> public string GLCODE { get; internal set; } /// <summary> /// What GST applies to this fee /// [Uppercase Alphanumeric (4)] /// </summary> public string GST_TYPE { get; internal set; } /// <summary> /// For every fee there is a subprogram /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// A subprogram always belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GLPROGRAM { get; internal set; } /// <summary> /// Fee might belong to an Initiative /// [Uppercase Alphanumeric (3)] /// </summary> public string INITIATIVE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// GL (General Ledger) related entity by [SDFC.GLCODE]-&gt;[GL.CODE] /// One GL key for each category /// </summary> public GL GLCODE_GL { get { if (GLCODE == null) { return null; } if (Cache_GLCODE_GL == null) { Cache_GLCODE_GL = Context.GL.FindByCODE(GLCODE); } return Cache_GLCODE_GL; } } /// <summary> /// KGST (GST Percentages) related entity by [SDFC.GST_TYPE]-&gt;[KGST.KGSTKEY] /// What GST applies to this fee /// </summary> public KGST GST_TYPE_KGST { get { if (GST_TYPE == null) { return null; } if (Cache_GST_TYPE_KGST == null) { Cache_GST_TYPE_KGST = Context.KGST.FindByKGSTKEY(GST_TYPE); } return Cache_GST_TYPE_KGST; } } /// <summary> /// KGLSUB (General Ledger Sub Programs) related entity by [SDFC.SUBPROGRAM]-&gt;[KGLSUB.SUBPROGRAM] /// For every fee there is a subprogram /// </summary> public KGLSUB SUBPROGRAM_KGLSUB { get { if (SUBPROGRAM == null) { return null; } if (Cache_SUBPROGRAM_KGLSUB == null) { Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM); } return Cache_SUBPROGRAM_KGLSUB; } } /// <summary> /// KGLINIT (General Ledger Initiatives) related entity by [SDFC.INITIATIVE]-&gt;[KGLINIT.INITIATIVE] /// Fee might belong to an Initiative /// </summary> public KGLINIT INITIATIVE_KGLINIT { get { if (INITIATIVE == null) { return null; } if (Cache_INITIATIVE_KGLINIT == null) { Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE); } return Cache_INITIATIVE_KGLINIT; } } #endregion #region Foreign Navigation Properties /// <summary> /// DRF (DR Transactions) related entities by [SDFC.SDFCKEY]-&gt;[DRF.FEE_CODE] /// Prime Key /// </summary> public IReadOnlyList<DRF> SDFCKEY_DRF_FEE_CODE { get { if (Cache_SDFCKEY_DRF_FEE_CODE == null && !Context.DRF.TryFindByFEE_CODE(SDFCKEY, out Cache_SDFCKEY_DRF_FEE_CODE)) { Cache_SDFCKEY_DRF_FEE_CODE = new List<DRF>().AsReadOnly(); } return Cache_SDFCKEY_DRF_FEE_CODE; } } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using io = System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; using Microsoft.Deployment.WindowsInstaller; using sys = System.Windows.Forms; using System.Drawing.Imaging; using System.Diagnostics; namespace WixSharp { /*http://www.codeproject.com/Articles/132918/Creating-Custom-Action-for-WIX-Written-in-Managed * Expected to be like this: * Property Name Install Uninstall Repair Modify Upgrade * -------------------------------------------------------------------------------------- * Installed False True False True True * REINSTALL True False True False False * UPGRADINGPRODUCTCODE True False True True True * * Though in the reality it is like this: * Property Name Install Uninstall Repair Modify Upgrade * --------------------------------------------------------------------------------------------------- * Installed <null> 00:00:00 00:00:00 00:00:00 <00:00:00> * REINSTALL <null> <null> All <null> <null> * UPGRADINGPRODUCTCODE <null> <null> <null> <null> <not empty> * * */ /// <summary> /// Represents MSI runtime context. This class is to be used by ManagedUI dialogs to interact with the MSI session. /// </summary> public class MsiRuntime : InstallerRuntime { /// <summary> /// The session object. /// </summary> public Session MsiSession { get; } /// <summary> /// Initializes a new instance of the <see cref="MsiRuntime"/> class. /// </summary> /// <param name="session">The session.</param> public MsiRuntime(Session session) : base(new MsiSessionAdapter(session)) { MsiSession = session; } /// <summary> /// Invokes Client Handlers /// </summary> /// <param name="eventName"></param> /// <param name="UIShell"></param> /// <returns></returns> public override ActionResult InvokeClientHandlers(string eventName, IShellView UIShell = null) { return ManagedProject.InvokeClientHandlers(MsiSession, eventName, UIShell); } //DOESN'T work reliably. For example if no InstallDir dialog is displayed the MSI session does not have "INSTALLDIR" property initialized. //The other properties (e.g. UI Level) are even never available at all. //It looks like Session is initialized/updated correctly for the 'custom actions' session but not for the 'Embedded UI' session. //In fact because of these problems a session object can no longer be considered as a single connection point between all MSI runtime modules. internal void CaptureSessionData() { try { if (MsiSession.IsActive()) { Data["INSTALLDIR"] = Session["INSTALLDIR"]; Data["Installed"] = Session["Installed"]; Data["REMOVE"] = Session["REMOVE"]; Data["REINSTALL"] = Session["REINSTALL"]; Data["UPGRADINGPRODUCTCODE"] = Session["UPGRADINGPRODUCTCODE"]; Data["UILevel"] = Session["UILevel"]; Data["WIXSHARP_MANAGED_UI_HANDLE"] = Session["WIXSHARP_MANAGED_UI_HANDLE"]; } } catch { } } } /// <summary> /// Represents MSI runtime context. This class is to be used by ManagedUI dialogs to interact with the MSI session. /// </summary> public class InstallerRuntime { /// <summary> /// Starts the execution of the MSI installation. /// </summary> public System.Action StartExecute { get; set; } /// <summary> /// Cancels the execution of the MSI installation, which is already started (progress is displayed). /// </summary> public System.Action CancelExecute { get; set; } /// <summary> /// The session object. /// </summary> public readonly ISession Session; /// <summary> /// Invokes Client Handlers /// </summary> /// <param name="eventName"></param> /// <param name="UIShell"></param> /// <returns></returns> public virtual ActionResult InvokeClientHandlers(string eventName, IShellView UIShell = null) { return ActionResult.Success; } /// <summary> /// Repository of the session properties to be captured and transfered to the deferred CAs. /// </summary> public Dictionary<string, string> Data { get; } = new Dictionary<string, string>(); /// <summary> /// Localization map. /// </summary> public ResourcesData UIText = new ResourcesData(); internal void FetchInstallDir() { string installDirProperty = this.Session.Property("WixSharp_UI_INSTALLDIR"); string dir = this.Session.Property(installDirProperty); if (dir.IsNotEmpty()) InstallDir = dir; //user entered INSTALLDIR else InstallDir = this.Session.GetDirectoryPath(installDirProperty); //default INSTALLDIR } /// <summary> /// Initializes a new instance of the <see cref="InstallerRuntime"/> class. /// </summary> /// <param name="session">The session.</param> public InstallerRuntime(ISession session) { this.Session = session; try { var bytes = TryReadBinary(Session, "WixSharp_UIText"); UIText.InitFromWxl(bytes); ProductName = Session.Property("ProductName"); ProductCode = Session.Property("ProductCode"); ProductVersion = session.Property("ProductVersion"); FetchInstallDir(); //it is important to preserve some product properties for localization as at the end of setup the session object will no longer be available UIText["ProductName"] = ProductName; UIText["ProductCode"] = ProductCode; UIText["ProductVersion"] = ProductVersion; //ensure Wix# strings are added if not already present if (!UIText.ContainsKey("ViewLog")) UIText["ViewLog"] = "View Log"; } catch { } } /// <summary> /// Gets the bitmap from the MSI embedded resources ('Binary' table). /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public Bitmap GetMsiBitmap(string name) { try { byte[] data = ReadBinary(Session, name); using (Stream s = new MemoryStream(data)) return (Bitmap)Bitmap.FromStream(s); } catch { } return null; } private static byte[] ReadBinary(ISession session, string binary) { return session.GetResourceData(binary); } private static byte[] TryReadBinary(ISession session, string binary) { try { return ReadBinary(session, binary); } catch { return null; } } /// <summary> /// Localizes the specified text. /// <para>The localization is performed according two possible scenarios. The method will return the match form the MSI embedded localization file. /// However if it cannot find the match the method will try to find the and return the match from the MSI session properties.</para> /// <para>This method is mainly used by 'LocalizeWith' extension for a single step localization of WinForm controls.</para> /// </summary> /// <param name="text">The text.</param> /// <returns></returns> public string Localize(string text) { if (UIText.ContainsKey(text)) return UIText[text]; try { string result = Session.Property(text); if (result.IsEmpty()) return text; else return result; } catch { } return text; } /// <summary> /// The product name /// </summary> public string ProductName; /// <summary> /// The directory the product is to be installed. This field will contain a valid path only after the MSI execution started. /// </summary> public string InstallDir { get; internal set; } /// <summary> /// The product code /// </summary> public string ProductCode; /// <summary> /// The product version /// </summary> public string ProductVersion; } /// <summary> /// Localization map. It is nothing else but a specialized version of a generic string-to-string Dictionary. /// </summary> public class ResourcesData : Dictionary<string, string> { /// <summary> /// Initializes from WiX localization data (*.wxl). /// </summary> /// <param name="wxlData">The WXL file bytes.</param> /// <returns></returns> public void InitFromWxl(byte[] wxlData) { this.Clear(); if (wxlData != null && wxlData.Any()) { XDocument doc; var tempXmlFile = System.IO.Path.GetTempFileName(); try { System.IO.File.WriteAllBytes(tempXmlFile, wxlData); doc = XDocument.Load(tempXmlFile); //important to use Load as it will take care about encoding magic first bites of wxlData, that came from the localization file } catch { throw new Exception("The localization XML data is in invalid format."); } finally { System.IO.File.Delete(tempXmlFile); } var data = doc.Descendants() .Where(x => x.Name.LocalName == "String") .ToDictionary(x => x.Attribute("Id").Value, x => x.Value); foreach (var item in data) this.Add(item.Key, item.Value); } } /// <summary> /// Gets or sets the value associated with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public new string this[string key] { get { return base.ContainsKey(key) ? base[key] : null; } set { base[key] = value; } } } }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using AdvanceMath; using AdvanceMath.Geometry2D; namespace Physics2DDotNet.Shapes { /// <summary> /// A Circle /// </summary> [Serializable] public sealed class CircleShape : IShape, IRaySegmentsCollidable, ILineFluidAffectable, IExplosionAffectable { #region fields private Scalar radius; private object tag; private Scalar inertia; private Vector2D[] vertexNormals; private Vector2D[] vertexes; #endregion #region constructors /// <summary> /// Creates a new Circle Instance. /// </summary> /// <param name="radius">how large the circle is.</param> /// <param name="vertexCount"> /// The number or vertex that will be generated along the perimeter of the circle. /// This is for collision detection. /// </param> public CircleShape(Scalar radius, int vertexCount) : this(radius, vertexCount, MassInfo.InertiaOfSolidCylinder(radius)) { } /// <summary> /// Creates a new Circle Instance. /// </summary> /// <param name="radius">how large the circle is.</param> /// <param name="vertexCount"> /// The number or vertex that will be generated along the perimeter of the circle. /// This is for collision detection. /// </param> /// <param name="inertia"> /// How hard it is to turn the shape. Depending on the construtor in the /// Body this will be multiplied with the mass to determine the moment of inertia. /// </param> public CircleShape(Scalar radius, int vertexCount, Scalar inertia) { if (radius <= 0) { throw new ArgumentOutOfRangeException("radius", "must be larger then zero"); } if (vertexCount < 3) { throw new ArgumentOutOfRangeException("vertexCount", "Must be equal or greater then 3"); } this.vertexes = VertexHelper.CreateCircle(radius, vertexCount); this.vertexNormals = VertexHelper.CreateCircle(1, vertexCount); this.inertia = inertia; this.radius = radius; } #endregion #region properties public object Tag { get { return tag; } set { tag = value; } } public Vector2D[] Vertexes { get { return vertexes; } } public Vector2D[] VertexNormals { get { return vertexNormals; } } public Scalar Inertia { get { return inertia; } } public Vector2D Centroid { get { return Vector2D.Zero; } } public Scalar Area { get { return radius * radius * MathHelper.Pi; } } /// <summary> /// the distance from the position where the circle ends. /// </summary> public Scalar Radius { get { return radius; } } public bool CanGetIntersection { get { return true; } } public bool CanGetCustomIntersection { get { return false; } } #endregion #region methods public void CalcBoundingRectangle(ref Matrix2x3 matrix, out BoundingRectangle rectangle) { BoundingRectangle.FromCircle(ref matrix, ref radius, out rectangle); } public void GetDistance(ref Vector2D point, out Scalar result) { Vector2D.GetMagnitude(ref point, out result); result -= radius; } public bool TryGetIntersection(Vector2D point, out IntersectionInfo info) { info.Position = point; Vector2D.Normalize(ref point, out info.Distance, out info.Normal); info.Distance -= radius; return info.Distance <= 0; } public bool TryGetCustomIntersection(Body self, Body other, out object customIntersectionInfo) { throw new NotSupportedException(); } bool IRaySegmentsCollidable.TryGetRayCollision(Body thisBody, Body raysBody, RaySegmentsShape raySegments, out RaySegmentIntersectionInfo info) { bool intersects = false; RaySegment[] segments = raySegments.Segments; Scalar[] result = new Scalar[segments.Length]; BoundingCircle bounding = new BoundingCircle(Vector2D.Zero, this.radius); Matrix2x3 vertexM = thisBody.Matrices.ToBody * raysBody.Matrices.ToWorld; for (int index = 0; index < segments.Length; ++index) { RaySegment segment = segments[index]; Ray ray2; Vector2D.Transform(ref vertexM, ref segment.RayInstance.Origin, out ray2.Origin); Vector2D.TransformNormal(ref vertexM, ref segment.RayInstance.Direction, out ray2.Direction); Scalar temp; bounding.Intersects(ref ray2, out temp); if (temp >= 0 && temp <= segment.Length) { intersects = true; result[index] = temp; continue; } else { result[index] = -1; } } if (intersects) { info = new RaySegmentIntersectionInfo(result); } else { info = null; } return intersects; } DragInfo IGlobalFluidAffectable.GetFluidInfo(Vector2D tangent) { return new DragInfo(Vector2D.Zero, radius * 2); } FluidInfo ILineFluidAffectable.GetFluidInfo(GetTangentCallback callback, Line line) { return ShapeHelper.GetFluidInfo(Vertexes, callback, line); } DragInfo IExplosionAffectable.GetExplosionInfo(Matrix2x3 matrix, Scalar radius, GetTangentCallback callback) { //TODO: do this right! Vector2D[] vertexes2 = new Vector2D[Vertexes.Length]; for (int index = 0; index < vertexes2.Length; ++index) { vertexes2[index] = matrix * Vertexes[index]; } Vector2D[] inter = VertexHelper.GetIntersection(vertexes2, radius); if (inter.Length < 3) { return null; } Vector2D centroid = VertexHelper.GetCentroid(inter); Vector2D tangent = callback(centroid); Scalar min, max; ShapeHelper.GetProjectedBounds(inter, tangent, out min, out max); Scalar avg = (max + min) / 2; return new DragInfo(tangent * avg, max - min); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.MembershipService { internal class MembershipOracleData { private readonly Dictionary<SiloAddress, MembershipEntry> localTable; // all silos not including current silo private Dictionary<SiloAddress, SiloStatus> localTableCopy; // a cached copy of a local table, including current silo, for fast access private Dictionary<SiloAddress, SiloStatus> localTableCopyOnlyActive; // a cached copy of a local table, for fast access, including only active nodes and current silo (if active) private Dictionary<SiloAddress, string> localNamesTableCopy; // a cached copy of a map from SiloAddress to Silo Name, not including current silo, for fast access private List<SiloAddress> localMultiClusterGatewaysCopy; // a cached copy of the silos that are designated gateways private readonly List<ISiloStatusListener> statusListeners; private readonly Logger logger; private IntValueStatistic clusterSizeStatistic; private StringValueStatistic clusterStatistic; internal readonly DateTime SiloStartTime; internal readonly SiloAddress MyAddress; internal readonly string MyHostname; internal SiloStatus CurrentStatus { get; private set; } // current status of this silo. internal string SiloName { get; private set; } // name of this silo. private readonly bool multiClusterActive; // set by configuration if multicluster is active private readonly int maxMultiClusterGateways; // set by configuration private UpdateFaultCombo myFaultAndUpdateZones; internal MembershipOracleData(Silo silo, Logger log) { logger = log; localTable = new Dictionary<SiloAddress, MembershipEntry>(); localTableCopy = new Dictionary<SiloAddress, SiloStatus>(); localTableCopyOnlyActive = new Dictionary<SiloAddress, SiloStatus>(); localNamesTableCopy = new Dictionary<SiloAddress, string>(); localMultiClusterGatewaysCopy = new List<SiloAddress>(); statusListeners = new List<ISiloStatusListener>(); SiloStartTime = DateTime.UtcNow; MyAddress = silo.SiloAddress; MyHostname = silo.LocalConfig.DNSHostName; SiloName = silo.LocalConfig.SiloName; this.multiClusterActive = silo.GlobalConfig.HasMultiClusterNetwork; this.maxMultiClusterGateways = silo.GlobalConfig.MaxMultiClusterGateways; CurrentStatus = SiloStatus.Created; clusterSizeStatistic = IntValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER_SIZE, () => localTableCopyOnlyActive.Count); clusterStatistic = StringValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER, () => { List<string> list = localTableCopyOnlyActive.Keys.Select(addr => addr.ToLongString()).ToList(); list.Sort(); return Utils.EnumerableToString(list); }); } // ONLY access localTableCopy and not the localTable, to prevent races, as this method may be called outside the turn. internal SiloStatus GetApproximateSiloStatus(SiloAddress siloAddress) { var status = SiloStatus.None; if (siloAddress.Equals(MyAddress)) { status = CurrentStatus; } else { if (!localTableCopy.TryGetValue(siloAddress, out status)) { if (CurrentStatus == SiloStatus.Active) if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100209, "-The given siloAddress {0} is not registered in this MembershipOracle.", siloAddress.ToLongString()); status = SiloStatus.None; } } if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatus returned {0} for silo: {1}", status, siloAddress.ToLongString()); return status; } // ONLY access localTableCopy or localTableCopyOnlyActive and not the localTable, to prevent races, as this method may be called outside the turn. internal Dictionary<SiloAddress, SiloStatus> GetApproximateSiloStatuses(bool onlyActive = false) { Dictionary<SiloAddress, SiloStatus> dict = onlyActive ? localTableCopyOnlyActive : localTableCopy; if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatuses returned {0} silos: {1}", dict.Count, Utils.DictionaryToString(dict)); return dict; } internal List<SiloAddress> GetApproximateMultiClusterGateways() { if (logger.IsVerbose3) logger.Verbose3("-GetApproximateMultiClusterGateways returned {0} silos: {1}", localMultiClusterGatewaysCopy.Count, string.Join(",", localMultiClusterGatewaysCopy)); return localMultiClusterGatewaysCopy; } internal bool TryGetSiloName(SiloAddress siloAddress, out string siloName) { if (siloAddress.Equals(MyAddress)) { siloName = SiloName; return true; } return localNamesTableCopy.TryGetValue(siloAddress, out siloName); } internal bool SubscribeToSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } internal bool UnSubscribeFromSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } internal void UpdateMyStatusLocal(SiloStatus status) { if (CurrentStatus == status) return; // make copies var tmpLocalTableCopy = GetSiloStatuses(st => true, true); // all the silos including me. var tmpLocalTableCopyOnlyActive = GetSiloStatuses(st => st == SiloStatus.Active, true); // only active silos including me. var tmpLocalTableNamesCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me. CurrentStatus = status; tmpLocalTableCopy[MyAddress] = status; if (status == SiloStatus.Active) { tmpLocalTableCopyOnlyActive[MyAddress] = status; } else if (tmpLocalTableCopyOnlyActive.ContainsKey(MyAddress)) { tmpLocalTableCopyOnlyActive.Remove(MyAddress); } localTableCopy = tmpLocalTableCopy; localTableCopyOnlyActive = tmpLocalTableCopyOnlyActive; localNamesTableCopy = tmpLocalTableNamesCopy; if (this.multiClusterActive) localMultiClusterGatewaysCopy = DetermineMultiClusterGateways(); NotifyLocalSubscribers(MyAddress, CurrentStatus); } private SiloStatus GetSiloStatus(SiloAddress siloAddress) { if (siloAddress.Equals(MyAddress)) return CurrentStatus; MembershipEntry data; return !localTable.TryGetValue(siloAddress, out data) ? SiloStatus.None : data.Status; } internal MembershipEntry GetSiloEntry(SiloAddress siloAddress) { return localTable[siloAddress]; } internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself) { Dictionary<SiloAddress, SiloStatus> dict = localTable.Where( pair => filter(pair.Value.Status)).ToDictionary(pair => pair.Key, pair => pair.Value.Status); if (includeMyself && filter(CurrentStatus)) // add myself dict.Add(MyAddress, CurrentStatus); return dict; } internal MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloStatus myStatus) { return CreateNewMembershipEntry(nodeConf, MyAddress, MyHostname, myStatus, SiloStartTime); } private static MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloAddress myAddress, string myHostname, SiloStatus myStatus, DateTime startTime) { var assy = Assembly.GetEntryAssembly() ?? typeof(MembershipOracleData).GetTypeInfo().Assembly; var roleName = assy.GetName().Name; var entry = new MembershipEntry { SiloAddress = myAddress, HostName = myHostname, SiloName = nodeConf.SiloName, Status = myStatus, ProxyPort = (nodeConf.IsGatewayNode ? nodeConf.ProxyGatewayEndpoint.Port : 0), RoleName = roleName, SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(), StartTime = startTime, IAmAliveTime = DateTime.UtcNow }; return entry; } internal void UpdateMyFaultAndUpdateZone(MembershipEntry entry) { this.myFaultAndUpdateZones = new UpdateFaultCombo(entry.UpdateZone, entry.FaultZone); } internal bool TryUpdateStatusAndNotify(MembershipEntry entry) { if (!TryUpdateStatus(entry)) return false; localTableCopy = GetSiloStatuses(status => true, true); // all the silos including me. localTableCopyOnlyActive = GetSiloStatuses(status => status == SiloStatus.Active, true); // only active silos including me. localNamesTableCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me. if (this.multiClusterActive) localMultiClusterGatewaysCopy = DetermineMultiClusterGateways(); if (logger.IsVerbose) logger.Verbose("-Updated my local view of {0} status. It is now {1}.", entry.SiloAddress.ToLongString(), GetSiloStatus(entry.SiloAddress)); NotifyLocalSubscribers(entry.SiloAddress, entry.Status); return true; } // return true if the status changed private bool TryUpdateStatus(MembershipEntry updatedSilo) { MembershipEntry currSiloData = null; if (!localTable.TryGetValue(updatedSilo.SiloAddress, out currSiloData)) { // an optimization - if I learn about dead silo and I never knew about him before, I don't care, can just ignore him. if (updatedSilo.Status == SiloStatus.Dead) return false; localTable.Add(updatedSilo.SiloAddress, updatedSilo); return true; } if (currSiloData.Status == updatedSilo.Status) return false; currSiloData.Update(updatedSilo); return true; } private void NotifyLocalSubscribers(SiloAddress siloAddress, SiloStatus newStatus) { if (logger.IsVerbose2) logger.Verbose2("-NotifyLocalSubscribers about {0} status {1}", siloAddress.ToLongString(), newStatus); List<ISiloStatusListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (ISiloStatusListener listener in copy) { try { listener.SiloStatusChangeNotification(siloAddress, newStatus); } catch (Exception exc) { logger.Error(ErrorCode.MembershipLocalSubscriberException, String.Format("Local ISiloStatusListener {0} has thrown an exception when was notified about SiloStatusChangeNotification about silo {1} new status {2}", listener.GetType().FullName, siloAddress.ToLongString(), newStatus), exc); } } } // deterministic function for designating the silos that should act as multi-cluster gateways private List<SiloAddress> DetermineMultiClusterGateways() { // function should never be called if we are not in a multicluster if (! this.multiClusterActive) throw new OrleansException("internal error: should not call this function without multicluster network"); // take all the active silos if their count does not exceed the desired number of gateways if (localTableCopyOnlyActive.Count <= this.maxMultiClusterGateways) return localTableCopyOnlyActive.Keys.ToList(); return DeterministicBalancedChoice<SiloAddress, UpdateFaultCombo>( localTableCopyOnlyActive.Keys, this.maxMultiClusterGateways, (SiloAddress a) => a.Equals(MyAddress) ? this.myFaultAndUpdateZones : new UpdateFaultCombo(localTable[a])); } // pick a specified number of elements from a set of candidates // - in a balanced way (try to pick evenly from groups) // - in a deterministic way (using sorting order on candidates and keys) internal static List<T> DeterministicBalancedChoice<T, K>(IEnumerable<T> candidates, int count, Func<T, K> group) where T:IComparable where K:IComparable { // organize candidates by groups var groups = new Dictionary<K, List<T>>(); var keys = new List<K>(); int numcandidates = 0; foreach (var c in candidates) { var key = group(c); List<T> list; if (!groups.TryGetValue(key, out list)) { groups[key] = list = new List<T>(); keys.Add(key); } list.Add(c); numcandidates++; } if (numcandidates < count) throw new ArgumentException("not enough candidates"); // sort the keys and the groups to guarantee deterministic result keys.Sort(); foreach(var kvp in groups) kvp.Value.Sort(); // pick round-robin from groups var result = new List<T>(); for (int i = 0; result.Count < count; i++) { var list = groups[keys[i % keys.Count]]; var col = i / keys.Count; if (col < list.Count) result.Add(list[col]); } return result; } internal struct UpdateFaultCombo : IComparable { public readonly int UpdateZone; public readonly int FaultZone; public UpdateFaultCombo(int updateZone, int faultZone) { UpdateZone = updateZone; FaultZone = faultZone; } public UpdateFaultCombo(MembershipEntry e) { UpdateZone = e.UpdateZone; FaultZone = e.FaultZone; } public int CompareTo(object x) { var other = (UpdateFaultCombo)x; int comp = UpdateZone.CompareTo(other.UpdateZone); if (comp != 0) return comp; return FaultZone.CompareTo(other.FaultZone); } } public override string ToString() { return string.Format("CurrentSiloStatus = {0}, {1} silos: {2}.", CurrentStatus, localTableCopy.Count, Utils.EnumerableToString(localTableCopy, pair => String.Format("SiloAddress={0} Status={1}", pair.Key.ToLongString(), pair.Value))); } } }
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using Acn.Rdm; using System.IO; using Acn.Packets.sAcn; using Acn.Sockets; using Acn.ArtNet.Packets; using Acn.ArtNet.IO; namespace Acn.ArtNet.Sockets { public class ArtNetSocket : Socket, IRdmSocket { public const int Port = 6454; public event UnhandledExceptionEventHandler UnhandledException; public event EventHandler<NewPacketEventArgs<ArtNetPacket>> NewPacket; public event EventHandler<NewPacketEventArgs<RdmPacket>> NewRdmPacket; public event EventHandler<NewPacketEventArgs<RdmPacket>> RdmPacketSent; public ArtNetSocket(UId rdmId) : base(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp) { RdmId = rdmId; } public ArtNetSocket() : this(UId.Empty) { } #region Information /// <summary> /// Gets or sets the RDM Id to use when sending packets. /// </summary> public UId RdmId { get; protected set; } private bool portOpen = false; public bool PortOpen { get { return portOpen; } set { portOpen = value; } } public IPAddress LocalIP { get; protected set; } public IPAddress LocalSubnetMask { get; protected set; } private static IPAddress GetBroadcastAddress(IPAddress address, IPAddress subnetMask) { byte[] ipAdressBytes = address.GetAddressBytes(); byte[] subnetMaskBytes = subnetMask.GetAddressBytes(); if (ipAdressBytes.Length != subnetMaskBytes.Length) throw new ArgumentException("Lengths of IP address and subnet mask do not match."); byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } return new IPAddress(broadcastAddress); } public IPAddress BroadcastAddress { get { if (LocalSubnetMask == null) return IPAddress.Broadcast; return GetBroadcastAddress(LocalIP, LocalSubnetMask); } } private DateTime? lastPacket = null; public DateTime? LastPacket { get { return lastPacket; } protected set { lastPacket = value; } } #endregion public void Open(IPAddress localIp, IPAddress localSubnetMask) { LocalIP = localIp; LocalSubnetMask = localSubnetMask; SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); Bind(new IPEndPoint(LocalIP, Port)); SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); PortOpen = true; StartReceive(); } public void StartReceive() { try { EndPoint localPort = new IPEndPoint(IPAddress.Any, Port); ArtNetReceiveData receiveState = new ArtNetReceiveData(); BeginReceiveFrom(receiveState.buffer, 0, receiveState.bufferSize, SocketFlags.None, ref localPort, new AsyncCallback(OnReceive), receiveState); } catch (Exception ex) { OnUnhandledException(new ApplicationException("An error ocurred while trying to start recieving ArtNet.", ex)); } } private void OnReceive(IAsyncResult state) { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); if (PortOpen) { try { ArtNetReceiveData receiveState = (ArtNetReceiveData)(state.AsyncState); if (receiveState != null) { receiveState.DataLength = EndReceiveFrom(state, ref remoteEndPoint); //Protect against UDP loopback where we receive our own packets. if (LocalEndPoint != remoteEndPoint && receiveState.Valid) { LastPacket = DateTime.Now; ProcessPacket((IPEndPoint)remoteEndPoint, ArtNetPacket.Create(receiveState)); } } } catch (Exception ex) { OnUnhandledException(ex); } finally { //Attempt to receive another packet. StartReceive(); } } } private void ProcessPacket(IPEndPoint source, ArtNetPacket packet) { if (packet != null) { if (NewPacket != null) NewPacket(this, new NewPacketEventArgs<ArtNetPacket>(source, packet)); ArtRdmPacket rdmPacket = packet as ArtRdmPacket; if (rdmPacket != null && NewRdmPacket != null) { RdmPacket rdm = RdmPacket.ReadPacket(new RdmBinaryReader(new MemoryStream(rdmPacket.RdmData))); NewRdmPacket(this, new NewPacketEventArgs<RdmPacket>(source, rdm)); } } } protected void OnUnhandledException(Exception ex) { if (UnhandledException != null) UnhandledException(this, new UnhandledExceptionEventArgs((object)ex, false)); } #region Sending public void Send(ArtNetPacket packet) { SendTo(packet.ToArray(), new IPEndPoint(BroadcastAddress, Port)); } public void Send(ArtNetPacket packet, RdmEndPoint address) { SendTo(packet.ToArray(), new IPEndPoint(address.IpAddress, Port)); } public void SendRdm(RdmPacket packet, RdmEndPoint targetAddress, UId targetId) { SendRdm(packet, targetAddress, targetId, RdmId); } public void SendRdm(RdmPacket packet, RdmEndPoint targetAddress, UId targetId, UId sourceId) { //Fill in addition details packet.Header.SourceId = sourceId; packet.Header.DestinationId = targetId; //Sub Devices if (targetId is SubDeviceUId) packet.Header.SubDevice = ((SubDeviceUId)targetId).SubDeviceId; //Create Rdm Packet MemoryStream rdmData = new MemoryStream(); RdmBinaryWriter rdmWriter = new RdmBinaryWriter(rdmData); //Write the RDM packet RdmPacket.WritePacket(packet, rdmWriter); //Write the checksum rdmWriter.WriteNetwork((short)(RdmPacket.CalculateChecksum(rdmData.GetBuffer()) + (int)RdmVersions.SubMessage + (int)DmxStartCodes.RDM)); //Create sACN Packet ArtRdmPacket rdmPacket = new ArtRdmPacket(); rdmPacket.Address = (byte)targetAddress.Universe; rdmPacket.SubStartCode = (byte)RdmVersions.SubMessage; rdmPacket.RdmData = rdmData.GetBuffer(); Send(rdmPacket, targetAddress); if (RdmPacketSent != null) RdmPacketSent(this, new NewPacketEventArgs<RdmPacket>(new IPEndPoint(targetAddress.IpAddress, Port), packet)); } public void SendRdm(List<RdmPacket> packets, RdmEndPoint targetAddress, UId targetId) { if (packets.Count < 1) throw new ArgumentException("Rdm packets list is empty."); RdmPacket primaryPacket = packets[0]; //Create sACN Packet ArtRdmSubPacket rdmPacket = new ArtRdmSubPacket(); rdmPacket.DeviceId = targetId; rdmPacket.RdmVersion = (byte)RdmVersions.SubMessage; rdmPacket.Command = primaryPacket.Header.Command; rdmPacket.ParameterId = primaryPacket.Header.ParameterId; rdmPacket.SubDevice = (short)primaryPacket.Header.SubDevice; rdmPacket.SubCount = (short)packets.Count; MemoryStream rdmData = new MemoryStream(); RdmBinaryWriter dataWriter = new RdmBinaryWriter(rdmData); foreach (RdmPacket item in packets) RdmPacket.WritePacket(item, dataWriter, true); rdmPacket.RdmData = rdmData.ToArray(); Send(rdmPacket, targetAddress); } #endregion protected override void Dispose(bool disposing) { PortOpen = false; base.Dispose(disposing); } } }
// 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>AdGroupAsset</c> resource.</summary> public sealed partial class AdGroupAssetName : gax::IResourceName, sys::IEquatable<AdGroupAssetName> { /// <summary>The possible contents of <see cref="AdGroupAssetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </summary> CustomerAdGroupAssetFieldType = 1, } private static gax::PathTemplate s_customerAdGroupAssetFieldType = new gax::PathTemplate("customers/{customer_id}/adGroupAssets/{ad_group_id_asset_id_field_type}"); /// <summary>Creates a <see cref="AdGroupAssetName"/> 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="AdGroupAssetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupAssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupAssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupAssetName"/> with the pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupAssetName"/> constructed from the provided ids.</returns> public static AdGroupAssetName FromCustomerAdGroupAssetFieldType(string customerId, string adGroupId, string assetId, string fieldTypeId) => new AdGroupAssetName(ResourceNameType.CustomerAdGroupAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAssetName"/> with pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAssetName"/> with pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string assetId, string fieldTypeId) => FormatCustomerAdGroupAssetFieldType(customerId, adGroupId, assetId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAssetName"/> with pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAssetName"/> with pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c>. /// </returns> public static string FormatCustomerAdGroupAssetFieldType(string customerId, string adGroupId, string assetId, string fieldTypeId) => s_customerAdGroupAssetFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId)))}"); /// <summary>Parses the given resource name string into a new <see cref="AdGroupAssetName"/> 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}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupAssetName"/> if successful.</returns> public static AdGroupAssetName Parse(string adGroupAssetName) => Parse(adGroupAssetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAssetName"/> 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}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAssetName">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="AdGroupAssetName"/> if successful.</returns> public static AdGroupAssetName Parse(string adGroupAssetName, bool allowUnparsed) => TryParse(adGroupAssetName, allowUnparsed, out AdGroupAssetName 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="AdGroupAssetName"/> 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}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAssetName"/>, 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 adGroupAssetName, out AdGroupAssetName result) => TryParse(adGroupAssetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAssetName"/> 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}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAssetName">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="AdGroupAssetName"/>, 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 adGroupAssetName, bool allowUnparsed, out AdGroupAssetName result) { gax::GaxPreconditions.CheckNotNull(adGroupAssetName, nameof(adGroupAssetName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupAssetFieldType.TryParseName(adGroupAssetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupAssetFieldType(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupAssetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupAssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string assetId = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; AssetId = assetId; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupAssetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/adGroupAssets/{ad_group_id}~{asset_id}~{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupAssetName(string customerId, string adGroupId, string assetId, string fieldTypeId) : this(ResourceNameType.CustomerAdGroupAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <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>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetId { 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>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { 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.CustomerAdGroupAssetFieldType: return s_customerAdGroupAssetFieldType.Expand(CustomerId, $"{AdGroupId}~{AssetId}~{FieldTypeId}"); 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 AdGroupAssetName); /// <inheritdoc/> public bool Equals(AdGroupAssetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupAssetName a, AdGroupAssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupAssetName a, AdGroupAssetName b) => !(a == b); } public partial class AdGroupAsset { /// <summary> /// <see cref="AdGroupAssetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupAssetName ResourceNameAsAdGroupAssetName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAssetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property. /// </summary> internal AdGroupName AdGroupAsAdGroupName { get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true); set => AdGroup = value?.ToString() ?? ""; } /// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary> internal AssetName AssetAsAssetName { get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true); set => Asset = value?.ToString() ?? ""; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnPermisosSesion class. /// </summary> [Serializable] public partial class PnPermisosSesionCollection : ActiveList<PnPermisosSesion, PnPermisosSesionCollection> { public PnPermisosSesionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnPermisosSesionCollection</returns> public PnPermisosSesionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnPermisosSesion o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_permisos_sesion table. /// </summary> [Serializable] public partial class PnPermisosSesion : ActiveRecord<PnPermisosSesion>, IActiveRecord { #region .ctors and Default Settings public PnPermisosSesion() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnPermisosSesion(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnPermisosSesion(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnPermisosSesion(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_permisos_sesion", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdPermisosSesion = new TableSchema.TableColumn(schema); colvarIdPermisosSesion.ColumnName = "id_permisos_sesion"; colvarIdPermisosSesion.DataType = DbType.Int32; colvarIdPermisosSesion.MaxLength = 0; colvarIdPermisosSesion.AutoIncrement = true; colvarIdPermisosSesion.IsNullable = false; colvarIdPermisosSesion.IsPrimaryKey = true; colvarIdPermisosSesion.IsForeignKey = false; colvarIdPermisosSesion.IsReadOnly = false; colvarIdPermisosSesion.DefaultSetting = @""; colvarIdPermisosSesion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPermisosSesion); TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema); colvarIdUsuario.ColumnName = "id_usuario"; colvarIdUsuario.DataType = DbType.Int32; colvarIdUsuario.MaxLength = 0; colvarIdUsuario.AutoIncrement = false; colvarIdUsuario.IsNullable = false; colvarIdUsuario.IsPrimaryKey = false; colvarIdUsuario.IsForeignKey = true; colvarIdUsuario.IsReadOnly = false; colvarIdUsuario.DefaultSetting = @""; colvarIdUsuario.ForeignKeyTableName = "PN_usuarios"; schema.Columns.Add(colvarIdUsuario); TableSchema.TableColumn colvarData = new TableSchema.TableColumn(schema); colvarData.ColumnName = "data"; colvarData.DataType = DbType.AnsiString; colvarData.MaxLength = -1; colvarData.AutoIncrement = false; colvarData.IsNullable = true; colvarData.IsPrimaryKey = false; colvarData.IsForeignKey = false; colvarData.IsReadOnly = false; colvarData.DefaultSetting = @""; colvarData.ForeignKeyTableName = ""; schema.Columns.Add(colvarData); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_permisos_sesion",schema); } } #endregion #region Props [XmlAttribute("IdPermisosSesion")] [Bindable(true)] public int IdPermisosSesion { get { return GetColumnValue<int>(Columns.IdPermisosSesion); } set { SetColumnValue(Columns.IdPermisosSesion, value); } } [XmlAttribute("IdUsuario")] [Bindable(true)] public int IdUsuario { get { return GetColumnValue<int>(Columns.IdUsuario); } set { SetColumnValue(Columns.IdUsuario, value); } } [XmlAttribute("Data")] [Bindable(true)] public string Data { get { return GetColumnValue<string>(Columns.Data); } set { SetColumnValue(Columns.Data, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a PnUsuario ActiveRecord object related to this PnPermisosSesion /// /// </summary> public DalSic.PnUsuario PnUsuario { get { return DalSic.PnUsuario.FetchByID(this.IdUsuario); } set { SetColumnValue("id_usuario", value.IdUsuario); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdUsuario,string varData) { PnPermisosSesion item = new PnPermisosSesion(); item.IdUsuario = varIdUsuario; item.Data = varData; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdPermisosSesion,int varIdUsuario,string varData) { PnPermisosSesion item = new PnPermisosSesion(); item.IdPermisosSesion = varIdPermisosSesion; item.IdUsuario = varIdUsuario; item.Data = varData; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdPermisosSesionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdUsuarioColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DataColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdPermisosSesion = @"id_permisos_sesion"; public static string IdUsuario = @"id_usuario"; public static string Data = @"data"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 9/7/2008 10:27:12 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace DotSpatial.Data { /// <summary> /// Numbers are based on the old school dbf definitions of data formats, and so can only store /// a very limited range of values. /// </summary> public class NumberConverter { /// <summary> /// Numbers can contain ASCII text up till 18 characters long, but no longer /// </summary> public const int MaximumLength = 18; ///<summary> /// Format provider to use to convert DBF numbers to strings and characters ///</summary> public static readonly IFormatProvider NumberConversionFormatProvider = CultureInfo.GetCultureInfo("en-US"); #region Private Variables private static readonly Random _rnd = new Random(); private int _decimalCount; // when the number is treated like a string, this is the number of recorded values after the decimal, plus one digit in front of the decimal. private int _length; // when the number is treated like a string, this is the total length, including minus signs and decimals. #endregion #region Constructors /// <summary> /// Creates a new instance of NumberConverter where the length and decimal count are known. /// </summary> public NumberConverter(int inLength, int inDecimalCount) { _length = inLength; _decimalCount = inDecimalCount; if (_length < 4) { _decimalCount = 0; } else if (_decimalCount > _length - 3) { _decimalCount = _length - 3; } UpdateDecimalFormatString(); } /// <summary> /// Cycles through the numeric values in the specified column and determines a selection of /// length and decimal count can accurately store the data. /// </summary> public NumberConverter(IList<double> values) { int maxExp = 0; int minExp = 0; for (int i = 0; i < values.Count; i++) { int exp = (int)Math.Log10(Math.Abs(values[i])); if (exp > MaximumLength - 1) { throw new NumberException(DataStrings.NumberException_TooLarge_S.Replace("%S", values[i].ToString())); } if (exp < -(MaximumLength - 1)) { throw new NumberException(DataStrings.NumberException_TooSmall_S.Replace("%S", values[i].ToString())); } if (exp > maxExp) maxExp = exp; if (exp < minExp) minExp = exp; if (exp < MaximumLength - 2) continue; // If this happens, we know that we need all the characters for values greater than 1, so no characters are left // for storing both the decimal itself and the numbers beyond the decimal. _length = MaximumLength; _decimalCount = 0; UpdateDecimalFormatString(); return; } UpdateDecimalFormatString(); } #endregion #region Methods /// <summary> /// Creates a new, random double that is constrained by the specified length and decimal count. /// </summary> /// <returns></returns> public double RandomDouble() { string test = new string(RandomChars(14)); return double.Parse(test); } /// <summary> /// Creates a new, random float that is constrained by the specified length and decimal count. /// </summary> /// <returns>A new float. Floats can only store about 8 digits of precision, so specifying a high </returns> public float RandomFloat() { string test = new string(RandomChars(6)); return float.Parse(test); } /// <summary> /// Creates a new, random decimal that is constrained by the specified length and decimal count. /// </summary> /// <returns></returns> public decimal RandomDecimal() { string test = new string(RandomChars(16)); return decimal.Parse(test); } /// <summary> /// Creates a new random array of characters that represents a number and is constrained by the specified length and decimal count /// </summary> /// <param name="numDigits">The integer number of significant (non-zero) digits that should be created as part of the number.</param> /// <returns>A character array of that matches the length and decimal count specified by this properties on this number converter</returns> public char[] RandomChars(int numDigits) { if (numDigits > _length - 1) { numDigits = _length - 1; // crop digits to length (reserve one spot for negative sign) } else if (numDigits < _length - 2) { if (_decimalCount > 0 && numDigits >= _decimalCount) numDigits += 1; // extend digits by decimal } bool isNegative = (_rnd.Next(0, 1) == 0); char[] c = new char[_length]; // i represents the distance from the end, moving backwards for (int i = 0; i < _length; i++) { if (_decimalCount > 0 && i == _decimalCount - 2) { c[i] = '.'; } else if (i < numDigits) { c[i] = (char)_rnd.Next(48, 57); } else if (i < _decimalCount - 2) { c[i] = '0'; } else { c[i] = ' '; } } if (isNegative) { c[numDigits] = '-'; } Array.Reverse(c); return c; } /// <summary> /// Converts from a string, or 0 if the parse failed /// </summary> /// <param name="value">The string value to parse</param> /// <returns></returns> public double FromString(string value) { double result; double.TryParse(value, out result); return result; } /// <summary> /// Converts the specified double value to a string that can be used for the number field /// </summary> /// <param name="number">The double precision floating point value to convert to a string</param> /// <returns>A string version of the specified number</returns> public string ToString(double number) { return ToStringInternal(number); } /// <summary> /// Converts the specified decimal value to a string that can be used for the number field /// </summary> /// <param name="number">The decimal value to convert to a string</param> /// <returns>A string version of the specified number</returns> public string ToString(decimal number) { return ToStringInternal(number); } /// <summary> /// Converts the specified float value to a string that can be used for the number field /// </summary> /// <param name="number">The floating point value to convert to a string</param> /// <returns>A string version of the specified number</returns> public string ToString(float number) { return ToStringInternal(number); } /// <summary> /// Converts the specified decimal value to a string that can be used for the number field /// </summary> /// <param name="number">The decimal value to convert to a string</param> /// <returns>A string version of the specified number</returns> public char[] ToChar(double number) { return ToCharInternal(number); } /// <summary> /// Converts the specified decimal value to a string that can be used for the number field /// </summary> /// <param name="number">The decimal value to convert to a string</param> /// <returns>A string version of the specified number</returns> public char[] ToChar(float number) { return ToCharInternal(number); } /// <summary> /// Converts the specified decimal value to a string that can be used for the number field /// </summary> /// <param name="number">The decimal value to convert to a string</param> /// <returns>A string version of the specified number</returns> public char[] ToChar(decimal number) { return ToCharInternal(number); } private char[] ToCharInternal(object number) { char[] c = new char[_length]; string str = String.Format(NumberConversionFormatProvider, DecimalFormatString, number); if (str.Length >= _length) { for (int i = 0; i < _length; i++) { c[i] = str[i]; // keep the left characters, and chop off lesser characters } } else { for (int i = 0; i < _length; i++) { int ci = i - (_length - str.Length); c[i] = ci < 0 ? ' ' : str[ci]; } } return c; } private string ToStringInternal(object number) { var sb = new StringBuilder(); var str = String.Format(NumberConversionFormatProvider, DecimalFormatString, number); for (var i = 0; i < _length - str.Length; i++) { sb.Append(' '); } sb.Append(str); return sb.ToString(); } /// <summary> /// Compute and update the DecimalFormatString from the precision specifier /// </summary> public void UpdateDecimalFormatString() { string format = "{0:"; for (int i = 0; i < _decimalCount; i++) { if (i == 0) format = format + "0."; format = format + "0"; } DecimalFormatString = format + "}"; } #endregion #region Properties /// <summary> /// Gets or set the length /// </summary> public int Length { get { return _length; } set { _length = value; } } /// <summary> /// Gets or sets the decimal count to use for this number converter /// </summary> public int DecimalCount { get { return _decimalCount; } set { _decimalCount = value; UpdateDecimalFormatString(); } } /// <summary> /// Gets or sets the format string used to convert doubles, floats, and decimals to strings /// </summary> public string DecimalFormatString { get; set; } #endregion } }
// // Copyright (C) Microsoft. All rights reserved. // using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Management.Automation.Runspaces; using System.Diagnostics.CodeAnalysis; using Dbg = System.Management.Automation; namespace Microsoft.WSMan.Management { #region Base class for cmdlets taking credential, authentication, certificatethumbprint /// <summary> /// Common base class for all WSMan cmdlets that /// take Authentication, CertificateThumbprint and Credential parameters /// </summary> public class AuthenticatingWSManCommand : PSCmdlet { /// <summary> /// The following is the definition of the input parameter "Credential". /// Specifies a user account that has permission to perform this action. The /// default is the current user. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Credential] [Alias("cred", "c")] public virtual PSCredential Credential { get { return credential; } set { credential = value; ValidateSpecifiedAuthentication(); } } private PSCredential credential; /// <summary> /// The following is the definition of the input parameter "Authentication". /// This parameter takes a set of authentication methods the user can select /// from. The available method are an enum called Authentication in the /// System.Management.Automation.Runspaces namespace. The available options /// should be as follows: /// - Default : Use the default authentication (ad defined by the underlying /// protocol) for establishing a remote connection. /// - Negotiate /// - Kerberos /// - Basic: Use basic authentication for establishing a remote connection. /// -CredSSP: Use CredSSP authentication for establishing a remote connection /// which will enable the user to perform credential delegation. (i.e. second /// hop) /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("auth", "am")] public virtual AuthenticationMechanism Authentication { get { return authentication; } set { authentication = value; ValidateSpecifiedAuthentication(); } } private AuthenticationMechanism authentication = AuthenticationMechanism.Default; /// <summary> /// Specifies the certificate thumbprint to be used to impersonate the user on the /// remote machine. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public virtual string CertificateThumbprint { get { return thumbPrint; } set { thumbPrint = value; ValidateSpecifiedAuthentication(); } } private string thumbPrint = null; internal void ValidateSpecifiedAuthentication() { WSManHelper.ValidateSpecifiedAuthentication( this.Authentication, this.Credential, this.CertificateThumbprint); } } #endregion #region Connect-WsMan /// <summary> /// connect wsman cmdlet /// </summary> [Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141437")] public class ConnectWSManCommand : AuthenticatingWSManCommand { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName", Position = 0)] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hash table and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("os")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "ComputerName")] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This hashtable can /// be created using New-WSManSessionOption /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("so")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; #endregion /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); if (connectionuri != null) { try { //always in the format http://server:port/applicationname string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } string crtComputerName = computername; if (crtComputerName == null) { crtComputerName = "localhost"; } if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); } helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); }//End BeginProcessing() }//end class #endregion # region Disconnect-WSMAN /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141439")] public class DisconnectWSManCommand : PSCmdlet, IDisposable { /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(Position = 0)] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(object session) { session = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); if (computername == null) { computername = "localhost"; } if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); } if (computername.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); } object _ws = helper.RemoveFromDictionary(computername); if (_ws != null) { Dispose(_ws); } else { helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); } }//End BeginProcessing() }//End Class #endregion Disconnect-WSMAN }
// 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 SubtractUInt32() { var test = new SimpleBinaryOpTest__SubtractUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 SimpleBinaryOpTest__SubtractUInt32 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[ElementCount]; private static UInt32[] _data2 = new UInt32[ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32> _dataTable; static SimpleBinaryOpTest__SubtractUInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Subtract( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Subtract( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractUInt32(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if ((uint)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((uint)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<UInt32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // MenuItems and in-Editor scripts for PhotonNetwork. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Reflection; using ExitGames.Client.Photon; using UnityEditor; using UnityEditorInternal; using UnityEngine; public class Text { public string WindowTitle = "PUN Wizard"; public string SetupWizardWarningTitle = "Warning"; public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking."; public string MainMenuButton = "Main Menu"; public string ConnectButton = "Connect to Photon Cloud"; public string UsePhotonLabel = "Using the Photon Cloud is free for development. If you don't have an account yet, enter your email and register."; public string SendButton = "Send"; public string EmailLabel = "Email:"; public string SignedUpAlreadyLabel = "I am already signed up. Let me enter my AppId."; public string SetupButton = "Setup"; public string RegisterByWebsiteLabel = "I want to register by a website."; public string AccountWebsiteButton = "Open account website"; public string SelfHostLabel = "I want to host my own server. Let me set it up."; public string SelfHostSettingsButton = "Open self-hosting settings"; public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile."; public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android."; public string EmailInUseLabel = "The provided e-mail-address has already been registered."; public string KnownAppIdLabel = "Ah, I know my Application ID. Get me to setup."; public string SeeMyAccountLabel = "Mh, see my account page"; public string SelfHostSettingButton = "Open self-hosting settings"; public string OopsLabel = "Oops!"; public string SeeMyAccountPage = ""; public string CancelButton = "Cancel"; public string PhotonCloudConnect = "Connect to Photon Cloud"; public string SetupOwnHostLabel = "Setup own Photon Host"; public string PUNWizardLabel = "Photon Unity Networking (PUN) Wizard"; public string SettingsButton = "Settings"; public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud."; public string WarningPhotonDisconnect = ""; public string ConverterLabel = "Converter"; public string StartButton = "Start"; public string UNtoPUNLabel = "Converts pure Unity Networking to Photon Unity Networking."; public string SettingsFileLabel = "Settings File"; public string LocateSettingsButton = "Locate settings asset"; public string SettingsHighlightLabel = "Highlights the used photon settings file in the project."; public string DocumentationLabel = "Documentation"; public string OpenPDFText = "Open PDF"; public string OpenPDFTooltip = "Opens the local documentation pdf."; public string OpenDevNetText = "Open DevNet"; public string OpenDevNetTooltip = "Online documentation for Photon."; public string OpenCloudDashboardText = "Open Cloud Dashboard"; public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics."; public string OpenForumText = "Open Forum"; public string OpenForumTooltip = "Online support for Photon."; public string QuestionsLabel = "Questions? Need help or want to give us feedback? You are most welcome!"; public string SeeForumButton = "See the Photon Forum"; public string OpenDashboardButton = "Open Dashboard (web)"; public string AppIdLabel = "Your AppId"; public string AppIdInfoLabel = "The AppId a Guid that identifies your game in the Photon Cloud. Find it on your dashboard page."; public string CloudRegionLabel = "Cloud Region"; public string RegionalServersInfo = "Photon Cloud has regional servers. Picking one near your customers improves ping times. You could use more than one but this setup does not support it."; public string SaveButton = "Save"; public string SettingsSavedTitle = "Success"; public string SettingsSavedMessage = "Saved your settings.\nConnectUsingSettings() will use the settings file."; public string OkButton = "Ok"; public string SeeMyAccountPageButton = "Mh, see my account page"; public string SetupOwnServerLabel = "Running my app in the cloud was fun but...\nLet me setup my own Photon server."; public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'."; public string ComparisonPageButton = "See comparison page"; public string YourPhotonServerLabel = "Your Photon Server"; public string AddressIPLabel = "Address/ip:"; public string PortLabel = "Port:"; public string LicensesLabel = "Licenses"; public string LicenseDownloadText = "Free License Download"; public string LicenseDownloadTooltip = "Get your free license for up to 100 concurrent players."; public string TryPhotonAppLabel = "Running my own server is too much hassle..\nI want to give Photon's free app a try."; public string GetCloudAppButton = "Get the free cloud app"; public string ConnectionTitle = "Connecting"; public string ConnectionInfo = "Connecting to the account service.."; public string ErrorTextTitle = "Error"; public string ServerSettingsMissingLabel = "Photon Unity Networking (PUN) is missing the 'ServerSettings' script. Re-import PUN to fix this."; public string MoreThanOneLabel = "There are more than one "; public string FilesInResourceFolderLabel = " files in 'Resources' folder. Check your project to keep only one. Using: "; public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!"; public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs"; public string FullRPCListTitle = "Warning: RPC-list is full!"; public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string SkipRPCListUpdateLabel = "Skip RPC-list update"; public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility"; public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients."; public string RPCListCleared = "Clear RPC-list"; public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings()."; public string BestRegionLabel = "best"; } [InitializeOnLoad] public class PhotonEditor : EditorWindow { public static Text CurrentLang = new Text(); protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun; protected Vector2 scrollPos = Vector2.zero; protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf"; protected static string UrlFreeLicense = "https://www.exitgames.com/en/OnPremise/Dashboard"; protected static string UrlDevNet = "http://doc.exitgames.com/en/pun/current/getting-started"; protected static string UrlForum = "http://forum.exitgames.com"; protected static string UrlCompare = "http://doc.exitgames.com/en/realtime/current/getting-started/onpremise-or-saas"; protected static string UrlHowToSetup = "http://doc.exitgames.com/en/onpremise/current/getting-started/photon-server-in-5min"; protected static string UrlAppIDExplained = "http://doc.exitgames.com/en/realtime/current/getting-started/obtain-your-app-id"; protected static string UrlAccountPage = "https://www.exitgames.com/Account/SignIn?email="; // opened in browser protected static string UrlCloudDashboard = "https://cloud.exitgames.com/Dashboard?email="; private enum GUIState { Uninitialized, Main, Setup } private enum PhotonSetupStates { RegisterForPhotonCloud, EmailAlreadyRegistered, SetupPhotonCloud, SetupSelfHosted } private GUIState guiState = GUIState.Uninitialized; private bool isSetupWizard = false; bool open = false; private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; private static double lastWarning = 0; private static bool postCompileActionsDone; private string photonAddress = "127.0.0.1"; // custom server private int photonPort = 5055; private ConnectionProtocol photonProtocol; private string emailAddress = string.Empty; private string cloudAppId = string.Empty; private static bool dontCheckPunSetupField; private static Texture2D HelpIcon; private static Texture2D WizardIcon; protected static Type WindowType = typeof(PhotonEditor); private static readonly string[] CloudServerRegionNames; private static CloudRegionCode selectedRegion; private bool helpRegion; private static bool isPunPlus; private static bool androidLibExists; private static bool iphoneLibExists; /// <summary> /// Can be used to (temporarily) disable the checks for PUN Setup and scene PhotonViews. /// This will prevent scene PhotonViews from being updated, so be careful. /// When you re-set this value, checks are used again and scene PhotonViews get IDs as needed. /// </summary> protected static bool dontCheckPunSetup { get { return dontCheckPunSetupField; } set { if (dontCheckPunSetupField != value) { dontCheckPunSetupField = value; } } } static PhotonEditor() { EditorApplication.projectWindowChanged += EditorUpdate; EditorApplication.hierarchyWindowChanged += EditorUpdate; EditorApplication.playmodeStateChanged += PlaymodeStateChanged; EditorApplication.update += OnUpdate; HelpIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/help.png", typeof(Texture2D)) as Texture2D; WizardIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/photoncloud-icon.png", typeof(Texture2D)) as Texture2D; // to be used in toolbar, the enum needs conversion to string[] being done here, once. Array enumValues = Enum.GetValues(typeof(CloudRegionCode)); CloudServerRegionNames = new string[enumValues.Length]; for (int i = 0; i < CloudServerRegionNames.Length; i++) { CloudServerRegionNames[i] = enumValues.GetValue(i).ToString(); if (CloudServerRegionNames[i].Equals("none")) { CloudServerRegionNames[i] = PhotonEditor.CurrentLang.BestRegionLabel; } } // detect optional packages PhotonEditor.CheckPunPlus(); } internal protected static bool CheckPunPlus() { androidLibExists = File.Exists("Assets/Plugins/Android/libPhotonSocketPlugin.so"); iphoneLibExists = File.Exists("Assets/Plugins/IPhone/libPhotonSocketPlugin.a"); isPunPlus = androidLibExists || iphoneLibExists; return isPunPlus; } private static void ImportWin8Support() { if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode) { return; // don't import while compiling } #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_5_1 || UNITY_5_2 const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage"; bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll"); if (!win8LibsExist && File.Exists(win8Package)) { AssetDatabase.ImportPackage(win8Package, false); } #endif } [MenuItem("Window/Photon Unity Networking/PUN Wizard &p")] protected static void Init() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.InitPhotonSetupWindow(); win.isSetupWizard = false; win.SwitchMenuState(GUIState.Main); } /// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary> protected static void ShowRegistrationWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.isSetupWizard = true; win.InitPhotonSetupWindow(); } /// <summary>Re-initializes the Photon Setup window and shows one of three states: register cloud, setup cloud, setup self-hosted.</summary> protected void InitPhotonSetupWindow() { this.minSize = MinSize; this.SwitchMenuState(GUIState.Setup); this.ReApplySettingsToWindow(); switch (PhotonEditor.Current.HostType) { case ServerSettings.HostingOption.PhotonCloud: case ServerSettings.HostingOption.BestRegion: this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; break; case ServerSettings.HostingOption.SelfHosted: this.photonSetupState = PhotonSetupStates.SetupSelfHosted; break; case ServerSettings.HostingOption.NotSet: default: this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; break; } } // called 100 times / sec private static void OnUpdate() { // after a compile, check RPCs to create a cache-list if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonEditor.Current != null) { #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_5_1 || UNITY_5_2 if (EditorApplication.isUpdating) return; #endif PhotonEditor.UpdateRpcList(); postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything) #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_5_1 || UNITY_5_2 PhotonEditor.ImportWin8Support(); #endif } } // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (dontCheckPunSetup || PhotonEditor.Current == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonEditor.Current.DisableAutoOpenWizard && PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) { ShowRegistrationWizard(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetwork.connected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetwork.Disconnect(); } } } // called in editor on change of play-mode (used to show a message popup that connection settings are incomplete) private static void PlaymodeStateChanged() { if (dontCheckPunSetup || EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode) { return; } if (PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) { EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton); } } private void SwitchMenuState(GUIState newState) { this.guiState = newState; if (this.isSetupWizard && newState != GUIState.Setup) { this.Close(); } } protected virtual void OnGUI() { PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed. GUI.SetNextControlName(""); this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); if (this.guiState == GUIState.Uninitialized) { this.ReApplySettingsToWindow(); this.guiState = (PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) ? GUIState.Setup : GUIState.Main; } if (this.guiState == GUIState.Main) { this.OnGuiMainWizard(); } else { this.OnGuiRegisterCloudApp(); } GUILayout.EndScrollView(); if (oldGuiState != this.photonSetupState) { GUI.FocusControl(""); } } protected virtual void OnGuiRegisterCloudApp() { GUI.skin.label.wordWrap = true; if (!this.isSetupWizard) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false))) { this.SwitchMenuState(GUIState.Main); } GUILayout.EndHorizontal(); GUILayout.Space(15); } if (this.photonSetupState == PhotonSetupStates.RegisterForPhotonCloud) { GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.ConnectButton); EditorGUILayout.Separator(); GUI.skin.label.fontStyle = FontStyle.Normal; GUILayout.Label(CurrentLang.UsePhotonLabel); EditorGUILayout.Separator(); this.emailAddress = EditorGUILayout.TextField(CurrentLang.EmailLabel, this.emailAddress); if (GUILayout.Button(CurrentLang.SendButton)) { GUIUtility.keyboardControl = 0; this.RegisterWithEmail(this.emailAddress); } GUILayout.Space(20); GUILayout.Label(CurrentLang.SignedUpAlreadyLabel); if (GUILayout.Button(CurrentLang.SetupButton)) { this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.RegisterByWebsiteLabel); if (GUILayout.Button(CurrentLang.AccountWebsiteButton)) { EditorUtility.OpenWithDefaultApp(UrlAccountPage + Uri.EscapeUriString(this.emailAddress)); } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.SelfHostLabel); if (GUILayout.Button(CurrentLang.SelfHostSettingsButton)) { this.photonSetupState = PhotonSetupStates.SetupSelfHosted; } GUILayout.FlexibleSpace(); if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); } EditorGUILayout.Separator(); } else if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered) { GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.OopsLabel); GUI.skin.label.fontStyle = FontStyle.Normal; GUILayout.Label(CurrentLang.EmailInUseLabel); if (GUILayout.Button(CurrentLang.SeeMyAccountPageButton)) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.KnownAppIdLabel); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } if (GUILayout.Button(CurrentLang.SetupButton)) { this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } GUILayout.EndHorizontal(); } else if (this.photonSetupState == PhotonSetupStates.SetupPhotonCloud) { // cloud setup GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.PhotonCloudConnect); GUI.skin.label.fontStyle = FontStyle.Normal; EditorGUILayout.Separator(); this.OnGuiSetupCloudAppId(); this.OnGuiCompareAndHelpOptions(); } else if (this.photonSetupState == PhotonSetupStates.SetupSelfHosted) { // self-hosting setup GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.SetupOwnHostLabel); GUI.skin.label.fontStyle = FontStyle.Normal; EditorGUILayout.Separator(); this.OnGuiSetupSelfhosting(); this.OnGuiCompareAndHelpOptions(); } } protected virtual void OnGuiMainWizard() { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(WizardIcon); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.PUNWizardLabel, EditorStyles.boldLabel); if (isPunPlus) { GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel); } else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); } EditorGUILayout.Separator(); // settings button GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel))) { this.InitPhotonSetupWindow(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // find / select settings asset GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsFileLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel))) { EditorGUIUtility.PingObject(PhotonEditor.Current); } GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); // converter GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.ConverterLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.StartButton, CurrentLang.UNtoPUNLabel))) { PhotonConverter.RunConversion(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // documentation GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip))) { EditorUtility.OpenWithDefaultApp(DocumentationLocation); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip))) { EditorUtility.OpenWithDefaultApp(UrlDevNet); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip))) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip))) { EditorUtility.OpenWithDefaultApp(UrlForum); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } protected virtual void OnGuiCompareAndHelpOptions() { GUILayout.FlexibleSpace(); GUILayout.Label(CurrentLang.QuestionsLabel); if (GUILayout.Button(CurrentLang.SeeForumButton)) { Application.OpenURL(UrlForum); } if (photonSetupState != PhotonSetupStates.SetupSelfHosted) { if (GUILayout.Button(CurrentLang.OpenDashboardButton)) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } } } protected virtual void OnGuiSetupCloudAppId() { GUILayout.Label(CurrentLang.AppIdLabel); GUILayout.BeginHorizontal(); this.cloudAppId = EditorGUILayout.TextField(this.cloudAppId); open = GUILayout.Toggle(open, HelpIcon, GUIStyle.none, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); if (open) GUILayout.Label(CurrentLang.AppIdInfoLabel); EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.CloudRegionLabel); GUILayout.BeginHorizontal(); int toolbarValue = GUILayout.Toolbar((int)selectedRegion, CloudServerRegionNames); // the enum CloudRegionCode is converted into a string[] in init (toolbar can't use enum) helpRegion = GUILayout.Toggle(helpRegion, HelpIcon, GUIStyle.none, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); if (helpRegion) GUILayout.Label(CurrentLang.RegionalServersInfo); PhotonEditor.selectedRegion = (CloudRegionCode)toolbarValue; EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { GUIUtility.keyboardControl = 0; this.ReApplySettingsToWindow(); } if (GUILayout.Button(CurrentLang.SaveButton)) { GUIUtility.keyboardControl = 0; this.cloudAppId = this.cloudAppId.Trim(); PhotonEditor.Current.UseCloud(this.cloudAppId); PhotonEditor.Current.PreferredRegion = PhotonEditor.selectedRegion; PhotonEditor.Current.HostType = (PhotonEditor.Current.PreferredRegion == CloudRegionCode.none) ? ServerSettings.HostingOption.BestRegion : ServerSettings.HostingOption.PhotonCloud; PhotonEditor.Save(); EditorGUIUtility.PingObject(PhotonEditor.Current); Selection.activeObject = PhotonEditor.Current; EditorUtility.DisplayDialog(CurrentLang.SettingsSavedTitle, CurrentLang.SettingsSavedMessage, CurrentLang.OkButton); } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.Label(CurrentLang.SetupOwnServerLabel); if (GUILayout.Button(CurrentLang.SelfHostSettingsButton)) { //this.photonAddress = ServerSettings.DefaultServerAddress; //this.photonPort = ServerSettings.DefaultMasterPort; this.photonSetupState = PhotonSetupStates.SetupSelfHosted; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } } protected virtual void OnGuiSetupSelfhosting() { GUILayout.Label(CurrentLang.YourPhotonServerLabel); this.photonAddress = EditorGUILayout.TextField(CurrentLang.AddressIPLabel, this.photonAddress); this.photonPort = EditorGUILayout.IntField(CurrentLang.PortLabel, this.photonPort); this.photonProtocol = (ConnectionProtocol)EditorGUILayout.EnumPopup("Protocol", this.photonProtocol); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { GUIUtility.keyboardControl = 0; this.ReApplySettingsToWindow(); } if (GUILayout.Button(CurrentLang.SaveButton)) { GUIUtility.keyboardControl = 0; PhotonEditor.Current.UseMyServer(this.photonAddress, this.photonPort, null); PhotonEditor.Current.Protocol = this.photonProtocol; PhotonEditor.Save(); EditorGUIUtility.PingObject(PhotonEditor.Current); Selection.activeObject = PhotonEditor.Current; EditorUtility.DisplayDialog(CurrentLang.SettingsSavedTitle, CurrentLang.SettingsSavedMessage, CurrentLang.OkButton); } GUILayout.EndHorizontal(); GUILayout.Space(20); // license GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.LicensesLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.LicenseDownloadText, CurrentLang.LicenseDownloadTooltip))) { EditorUtility.OpenWithDefaultApp(UrlFreeLicense); } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.Label(CurrentLang.TryPhotonAppLabel); if (GUILayout.Button(CurrentLang.GetCloudAppButton)) { this.cloudAppId = string.Empty; this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } } protected virtual void RegisterWithEmail(string email) { EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f); var client = new AccountService(); client.RegisterByEmail(email, RegisterOrigin); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client EditorUtility.ClearProgressBar(); if (client.ReturnCode == 0) { PhotonEditor.Current.UseCloud(client.AppId, 0); PhotonEditor.Save(); this.ReApplySettingsToWindow(); this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } else { if (client.Message.Contains(CurrentLang.EmailInUseLabel)) { this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered; } else { EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton); // Debug.Log(client.Exception); this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } } } #region SettingsFileHandling private static ServerSettings currentSettings; private Vector2 MinSize = new Vector2(350, 400); public static ServerSettings Current { get { if (currentSettings == null) { // find out if ServerSettings can be instantiated (existing script check) ScriptableObject serverSettingTest = CreateInstance("ServerSettings"); if (serverSettingTest == null) { Debug.LogError(CurrentLang.ServerSettingsMissingLabel); return null; } DestroyImmediate(serverSettingTest); // try to load settings from file ReLoadCurrentSettings(); // if still not loaded, create one if (currentSettings == null) { string settingsPath = Path.GetDirectoryName(PhotonNetwork.serverSettingsAssetPath); if (!Directory.Exists(settingsPath)) { Directory.CreateDirectory(settingsPath); AssetDatabase.ImportAsset(settingsPath); } currentSettings = (ServerSettings)ScriptableObject.CreateInstance("ServerSettings"); if (currentSettings != null) { AssetDatabase.CreateAsset(currentSettings, PhotonNetwork.serverSettingsAssetPath); } else { Debug.LogError(CurrentLang.ServerSettingsMissingLabel); } } // settings were loaded or created. set this editor's initial selected region now (will be changed in GUI) if (currentSettings != null) { selectedRegion = currentSettings.PreferredRegion; } } return currentSettings; } protected set { currentSettings = value; } } public static void Save() { EditorUtility.SetDirty(PhotonEditor.Current); } public static void ReLoadCurrentSettings() { // this now warns developers if there are more than one settings files in resources folders. first will be used. UnityEngine.Object[] settingFiles = Resources.LoadAll(PhotonNetwork.serverSettingsAssetFile, typeof(ServerSettings)); if (settingFiles != null && settingFiles.Length > 0) { PhotonEditor.Current = (ServerSettings)settingFiles[0]; if (settingFiles.Length > 1) { Debug.LogWarning(CurrentLang.MoreThanOneLabel + PhotonNetwork.serverSettingsAssetFile + CurrentLang.FilesInResourceFolderLabel + AssetDatabase.GetAssetPath(PhotonEditor.Current)); } } } protected void ReApplySettingsToWindow() { this.cloudAppId = string.IsNullOrEmpty(PhotonEditor.Current.AppID) ? string.Empty : PhotonEditor.Current.AppID; this.photonAddress = string.IsNullOrEmpty(PhotonEditor.Current.ServerAddress) ? string.Empty : PhotonEditor.Current.ServerAddress; this.photonPort = PhotonEditor.Current.ServerPort; this.photonProtocol = PhotonEditor.Current.Protocol; } public static void UpdateRpcList() { List<string> additionalRpcs = new List<string>(); HashSet<string> currentRpcs = new HashSet<string>(); var types = GetAllSubTypesInScripts(typeof(MonoBehaviour)); foreach (var mono in types) { MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (MethodInfo method in methods) { if (method.IsDefined(typeof(UnityEngine.RPC), false)) { currentRpcs.Add(method.Name); if (!additionalRpcs.Contains(method.Name) && !PhotonEditor.Current.RpcList.Contains(method.Name)) { additionalRpcs.Add(method.Name); } } } } if (additionalRpcs.Count > 0) { // LIMITS RPC COUNT if (additionalRpcs.Count + PhotonEditor.Current.RpcList.Count >= byte.MaxValue) { if (currentRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonEditor.Current.RpcList.Clear(); PhotonEditor.Current.RpcList.AddRange(currentRpcs); } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } additionalRpcs.Sort(); PhotonEditor.Current.RpcList.AddRange(additionalRpcs); EditorUtility.SetDirty(PhotonEditor.Current); } } public static void ClearRpcList() { bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton); if (clearList) { PhotonEditor.Current.RpcList.Clear(); Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning); } } public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass) { var result = new System.Collections.Generic.List<System.Type>(); System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (var A in AS) { // this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project if (!A.FullName.StartsWith("Assembly-")) { // Debug.Log("Skipping Assembly: " + A); continue; } //Debug.Log("Assembly: " + A.FullName); System.Type[] types = A.GetTypes(); foreach (var T in types) { if (T.IsSubclassOf(aBaseClass)) result.Add(T); } } return result.ToArray(); } #endregion }
//------------------------------------------------------------------------------ // <copyright file="DesignerTextViewAdapter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Globalization; using System.Text; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace System.Web.UI.Design.MobileControls.Adapters { [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class DesignerTextViewAdapter : System.Web.UI.MobileControls.Adapters.HtmlControlAdapter { protected new TextView Control { get { return (TextView)base.Control; } } public override MobileCapabilities Device { get { return DesignerCapabilities.Instance; } } public override void Render(HtmlMobileTextWriter writer) { Alignment alignment = (Alignment) Style[Style.AlignmentKey, true]; Wrapping wrapping = (Wrapping) Style[Style.WrappingKey, true]; bool wrap = (wrapping == Wrapping.Wrap || wrapping == Wrapping.NotSet); String width = DesignerAdapterUtil.GetWidth(Control); ((DesignerTextWriter)writer).EnterZeroFontSizeTag(); writer.WriteBeginTag("div"); if (!wrap) { byte templateStatus; int maxWidth = DesignerAdapterUtil.GetMaxWidthToFit(Control, out templateStatus); if (templateStatus == DesignerAdapterUtil.CONTROL_IN_TEMPLATE_EDIT) { width = maxWidth.ToString(CultureInfo.InvariantCulture) + "px"; } writer.WriteAttribute("style", "overflow-x:hidden;width:" + width); } else { writer.WriteAttribute("style", "word-wrap:break-word;width:" + width); } if (alignment != Alignment.NotSet) { writer.WriteAttribute("align", Enum.GetName(typeof(Alignment), alignment)); } writer.Write(">"); MSHTMLHostUtil.ApplyStyle(null, null, null); String filteredText = FilterTags(Control.Text.Trim()); int uniqueLineHeight = MSHTMLHostUtil.GetHtmlFragmentHeight("a"); int requiredHeight = MSHTMLHostUtil.GetHtmlFragmentHeight(filteredText); int requiredWidth = MSHTMLHostUtil.GetHtmlFragmentWidth(filteredText); ((DesignerTextWriter)writer).WriteCssStyleText(Style, null, (requiredHeight > uniqueLineHeight || requiredWidth > 1) ? filteredText : "&nbsp;", false); writer.WriteEndTag("div"); ((DesignerTextWriter)writer).ExitZeroFontSizeTag(); } private enum CursorStatus { OutsideTag, InsideTagName, InsideAttributeName, InsideAttributeValue, ExpectingAttributeValue } private String FilterTags(String text) { StringBuilder filteredText = new StringBuilder(); // StringBuilder hrefValue = null; int len = text.Length, i; int tagBegin = 0; //, attribBegin = 0; bool doubleQuotedAttributeValue = false; // bool cacheHRefValue = false; CursorStatus cs = CursorStatus.OutsideTag; String tagName = String.Empty; for (i = 0; i < len; i++) { switch (text[i]) { case '<': { switch (cs) { case CursorStatus.OutsideTag: { cs = CursorStatus.InsideTagName; tagBegin = i; break; } } break; } case '=': { switch (cs) { case CursorStatus.InsideAttributeName: { // cacheHRefValue = text.Substring(attribBegin, i-attribBegin).Trim().ToUpper() == "HREF"; // hrefValue = null; cs = CursorStatus.ExpectingAttributeValue; break; } case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } break; } case '"': { switch (cs) { case CursorStatus.ExpectingAttributeValue: { cs = CursorStatus.InsideAttributeValue; doubleQuotedAttributeValue = true; //if (cacheHRefValue) //{ // hrefValue = new StringBuilder("\""); //} break; } case CursorStatus.InsideAttributeValue: { //if (cacheHRefValue) //{ // hrefValue.Append('"'); //} if (text[i-1] != '\\' && doubleQuotedAttributeValue) { // leaving attribute value cs = CursorStatus.InsideAttributeName; // attribBegin = i; break; } break; } case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } break; } case '\'': { switch (cs) { case CursorStatus.ExpectingAttributeValue: { cs = CursorStatus.InsideAttributeValue; //if (cacheHRefValue) //{ // hrefValue = new StringBuilder("'"); //} doubleQuotedAttributeValue = false; break; } case CursorStatus.InsideAttributeValue: { //if (cacheHRefValue) //{ // hrefValue.Append('\''); //} if (text[i-1] != '\\' && !doubleQuotedAttributeValue) { // leaving attribute value cs = CursorStatus.InsideAttributeName; // attribBegin = i; break; } break; } case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } break; } case '/': { switch (cs) { case CursorStatus.InsideTagName: { tagName = text.Substring(tagBegin+1, i-tagBegin-1).Trim().ToUpper(CultureInfo.InvariantCulture); if (tagName.Trim().Length > 0) { cs = CursorStatus.InsideAttributeName; // attribBegin = i; } break; } case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } break; } case '>': { switch (cs) { case CursorStatus.InsideTagName: case CursorStatus.InsideAttributeName: case CursorStatus.ExpectingAttributeValue: { // leaving tag if (cs == CursorStatus.InsideTagName) { tagName = text.Substring(tagBegin+1, i-tagBegin-1).Trim().ToUpper(CultureInfo.InvariantCulture); } cs = CursorStatus.OutsideTag; switch (tagName) { case "A": { //filteredText.Append(String.Format("<A HREF={0}>", // hrefValue == null ? String.Empty : hrefValue.ToString())); filteredText.Append("<A HREF=\"\">"); break; } case "/A": case "B": case "/B": case "BR": case "/BR": case "I": case "/I": case "P": case "/P": { filteredText.Append("<" + tagName + ">"); break; } } tagName = String.Empty; break; } case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } break; } default: { if (Char.IsWhiteSpace(text[i])) { switch (cs) { case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } case CursorStatus.InsideTagName: { cs = CursorStatus.InsideAttributeName; // attribBegin = i; tagName = text.Substring(tagBegin+1, i-tagBegin-1).Trim().ToUpper(CultureInfo.InvariantCulture); break; } } } else { switch (cs) { case CursorStatus.OutsideTag: { filteredText.Append(text[i]); break; } } } break; } } } return filteredText.ToString(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Windows.Forms; namespace OpenLiveWriter.Controls { /// <summary> /// Provides a base class for lightweight button-type controls. Painting and layout is left /// to derived classes. /// </summary> public class ButtonBaseLightweightControl : LightweightControl { /// <summary> /// Required designer variable. /// </summary> private IContainer components = null; /// <summary> /// Gets the tool tip text to display for this ButtonBaseLightweightControl. /// </summary> protected virtual string ToolTipText { get { return null; } } /// <summary> /// A value indicating whether the mouse is inside the control. /// </summary> private bool mouseInside = false; /// <summary> /// Gets or sets a value indicating whether the mouse is inside the control. /// </summary> protected bool MouseInside { get { return mouseInside; } set { // Ensure that the property is actually changing. if (mouseInside != value) { // Update the value. mouseInside = value; Invalidate(); // Update the tool tip text, if the parent implements IToolTipDisplay. Note // that we set the tool tip text when the parent implements IToolTipDisplay so // an older tool tip will be erased if it was being displayed. if (Parent is IToolTipDisplay) { IToolTipDisplay toolTipDisplay = (IToolTipDisplay)Parent; if (mouseInside && !LeftMouseButtonDown) toolTipDisplay.SetToolTip(ToolTipText); else toolTipDisplay.SetToolTip(null); } } } } /// <summary> /// A value indicating whether the left mouse button is down. /// </summary> private bool leftMouseButtonDown = false; /// <summary> /// Gets or sets a value indicating whether the left mouse button is down. /// </summary> protected bool LeftMouseButtonDown { get { return leftMouseButtonDown; } set { // Ensure that the property is actually changing. if (leftMouseButtonDown != value) { leftMouseButtonDown = value; Invalidate(); } } } /// <summary> /// Occurs when the button is pushed. /// </summary> [ Category("Action"), Description("Occurs when the button is pushed.") ] public event EventHandler Pushed; /// <summary> /// Initializes a new instance of the ButtonBaseLightweightControl class. /// </summary> public ButtonBaseLightweightControl(IContainer container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container.Add(this); InitializeComponent(); // Initialize the object. InitializeObject(); } /// <summary> /// Initializes a new instance of the ButtonBaseLightweightControl class. /// </summary> public ButtonBaseLightweightControl() { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> InitializeComponent(); // Initialize the object. InitializeObject(); } /// <summary> /// Object initialization. /// </summary> private void InitializeObject() { // Set the default size. VirtualSize = DefaultVirtualSize; } #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() { components = new System.ComponentModel.Container(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion /// <summary> /// Raises the MouseDown event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data.</param> protected override void OnMouseDown(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseDown(e); // If the button is the left button, set the LeftMouseButtonDown property. if (e.Button == MouseButtons.Left) LeftMouseButtonDown = true; } /// <summary> /// Raises the MouseEnter event. /// </summary> /// <param name="e">A EventArgs that contains the event data.</param> protected override void OnMouseEnter(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseEnter(e); // Set the MouseInside property. MouseInside = true; } /// <summary> /// Raises the MouseLeave event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnMouseLeave(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseLeave(e); // Set the MouseInside property. MouseInside = false; } /// <summary> /// Raises the MouseMove event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data.</param> protected override void OnMouseMove(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseMove(e); // Update the state of the MouseInside property if the LeftMouseButtonDown property // is true. if (LeftMouseButtonDown) MouseInside = VirtualClientRectangle.Contains(e.X, e.Y); else MouseInside = true; } /// <summary> /// Raises the MouseUp event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data.</param> protected override void OnMouseUp(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseUp(e); // No mouse inside until it moves again. MouseInside = false; // If the button is the left button, set the LeftMouseButtonDown property. if (e.Button == MouseButtons.Left) { LeftMouseButtonDown = false; if (VirtualClientRectangle.Contains(e.X, e.Y)) OnPushed(EventArgs.Empty); } } /// <summary> /// Raises the Pushed event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnPushed(EventArgs e) { if (Pushed != null) Pushed(this, e); } } }
using System; using System.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Migrations.Initial; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Services; namespace Umbraco.Core.Persistence { public class DatabaseSchemaHelper { private readonly Database _db; private readonly ILogger _logger; private readonly ISqlSyntaxProvider _syntaxProvider; private readonly BaseDataCreation _baseDataCreation; public DatabaseSchemaHelper(Database db, ILogger logger, ISqlSyntaxProvider syntaxProvider) { _db = db; _logger = logger; _syntaxProvider = syntaxProvider; _baseDataCreation = new BaseDataCreation(db, logger); } public bool TableExist(string tableName) { return _syntaxProvider.DoesTableExist(_db, tableName); } public bool TableExist<T>() { var poco = Database.PocoData.ForType(typeof(T)); var tableName = poco.TableInfo.TableName; return TableExist(tableName); } internal void UninstallDatabaseSchema() { var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider); creation.UninstallDatabaseSchema(); } /// <summary> /// Creates the Umbraco db schema in the Database of the current Database. /// Safe method that is only able to create the schema in non-configured /// umbraco instances. /// </summary> public void CreateDatabaseSchema(ApplicationContext applicationContext) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); CreateDatabaseSchema(true, applicationContext); } /// <summary> /// Creates the Umbraco db schema in the Database of the current Database /// with the option to guard the db from having the schema created /// multiple times. /// </summary> /// <param name="guardConfiguration"></param> /// <param name="applicationContext"></param> public void CreateDatabaseSchema(bool guardConfiguration, ApplicationContext applicationContext) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); if (guardConfiguration && applicationContext.IsConfigured) throw new Exception("Umbraco is already configured!"); CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService); } internal void CreateDatabaseSchemaDo(bool guardConfiguration, ApplicationContext applicationContext) { if (guardConfiguration && applicationContext.IsConfigured) throw new Exception("Umbraco is already configured!"); CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService); } internal void CreateDatabaseSchemaDo(IMigrationEntryService migrationEntryService) { _logger.Info<Database>("Initializing database schema creation"); var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider); creation.InitializeDatabaseSchema(); _logger.Info<Database>("Finalized database schema creation"); } public void CreateTable<T>(bool overwrite) where T : new() { var tableType = typeof(T); CreateTable(overwrite, tableType); } public void CreateTable<T>() where T : new() { var tableType = typeof(T); CreateTable(false, tableType); } public void CreateTable(bool overwrite, Type modelType) { var tableDefinition = DefinitionFactory.GetTableDefinition(_syntaxProvider, modelType); var tableName = tableDefinition.Name; string createSql = _syntaxProvider.Format(tableDefinition); string createPrimaryKeySql = _syntaxProvider.FormatPrimaryKey(tableDefinition); var foreignSql = _syntaxProvider.Format(tableDefinition.ForeignKeys); var indexSql = _syntaxProvider.Format(tableDefinition.Indexes); var tableExist = TableExist(tableName); if (overwrite && tableExist) { DropTable(tableName); tableExist = false; } if (tableExist == false) { using (var transaction = _db.GetTransaction()) { //Execute the Create Table sql int created = _db.Execute(new Sql(createSql)); _logger.Info<Database>(string.Format("Create Table sql {0}:\n {1}", created, createSql)); //If any statements exists for the primary key execute them here if (!string.IsNullOrEmpty(createPrimaryKeySql)) { int createdPk = _db.Execute(new Sql(createPrimaryKeySql)); _logger.Info<Database>(string.Format("Primary Key sql {0}:\n {1}", createdPk, createPrimaryKeySql)); } //Turn on identity insert if db provider is not mysql if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity)) _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", _syntaxProvider.GetQuotedTableName(tableName)))); //Call the NewTable-event to trigger the insert of base/default data //OnNewTable(tableName, _db, e, _logger); _baseDataCreation.InitializeBaseData(tableName); //Turn off identity insert if db provider is not mysql if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity)) _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", _syntaxProvider.GetQuotedTableName(tableName)))); //Special case for MySql if (_syntaxProvider is MySqlSyntaxProvider && tableName.Equals("umbracoUser")) { _db.Update<UserDto>("SET id = @IdAfter WHERE id = @IdBefore AND userLogin = @Login", new { IdAfter = 0, IdBefore = 1, Login = "admin" }); } //Loop through index statements and execute sql foreach (var sql in indexSql) { int createdIndex = _db.Execute(new Sql(sql)); _logger.Info<Database>(string.Format("Create Index sql {0}:\n {1}", createdIndex, sql)); } //Loop through foreignkey statements and execute sql foreach (var sql in foreignSql) { int createdFk = _db.Execute(new Sql(sql)); _logger.Info<Database>(string.Format("Create Foreign Key sql {0}:\n {1}", createdFk, sql)); } transaction.Complete(); } } _logger.Info<Database>(string.Format("New table '{0}' was created", tableName)); } public void DropTable<T>() where T : new() { Type type = typeof(T); var tableNameAttribute = type.FirstAttribute<TableNameAttribute>(); if (tableNameAttribute == null) throw new Exception( string.Format( "The Type '{0}' does not contain a TableNameAttribute, which is used to find the name of the table to drop. The operation could not be completed.", type.Name)); string tableName = tableNameAttribute.Value; DropTable(tableName); } public void DropTable(string tableName) { var sql = new Sql(string.Format( _syntaxProvider.DropTable, _syntaxProvider.GetQuotedTableName(tableName))); _db.Execute(sql); } } }
// 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 gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAccountBudgetServiceClientTest { [Category("Autogenerated")][Test] public void GetAccountBudgetRequestObject() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetRequestObjectAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudget() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudgetResourceNames() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request.ResourceNameAsAccountBudgetName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetResourceNamesAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request.ResourceNameAsAccountBudgetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request.ResourceNameAsAccountBudgetName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (C) 2012-2014 DataStax 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; using System.Collections.Generic; using System.Threading; using System.Linq; namespace Cassandra { /// <summary> /// A data-center aware Round-robin load balancing policy. <p> This policy /// provides round-robin queries over the node of the local datacenter. It also /// includes in the query plans returned a configurable number of hosts in the /// remote datacenters, but those are always tried after the local nodes. In /// other words, this policy guarantees that no host in a remote datacenter will /// be queried unless no host in the local datacenter can be reached. </p><p> If used /// with a single datacenter, this policy is equivalent to the /// <see cref="RoundRobinPolicy"/> policy, but its GetDatacenter awareness /// incurs a slight overhead so the <see cref="RoundRobinPolicy"/> /// policy could be preferred to this policy in that case.</p> /// </summary> public class DCAwareRoundRobinPolicy : ILoadBalancingPolicy { private string _localDc; private readonly int _usedHostsPerRemoteDc; private readonly int _maxIndex = Int32.MaxValue - 10000; private volatile Tuple<List<Host>, List<Host>> _hosts; private Object _hostCreationLock = new Object(); ICluster _cluster; int _index; /// <summary> /// Creates a new datacenter aware round robin policy that auto-discover the local data-center. /// <para> /// If this constructor is used, the data-center used as local will the /// data-center of the first Cassandra node the driver connects to. This /// will always be ok if all the contact points use at <see cref="Cluster"/> /// creation are in the local data-center. If it's not the case, you should /// provide the local data-center name yourself by using one of the other /// constructor of this class. /// </para> /// </summary> public DCAwareRoundRobinPolicy() : this(null, 0) { } /// <summary> /// Creates a new datacenter aware round robin policy given the name of the local /// datacenter. <p> The name of the local datacenter provided must be the local /// datacenter name as known by Cassandra. </p><p> The policy created will ignore all /// remote hosts. In other words, this is equivalent to /// <c>new DCAwareRoundRobinPolicy(localDc, 0)</c>.</p> /// </summary> /// <param name="localDc"> the name of the local datacenter (as known by Cassandra).</param> public DCAwareRoundRobinPolicy(string localDc) : this(localDc, 0) { } ///<summary> /// Creates a new DCAwareRoundRobin policy given the name of the local /// datacenter and that uses the provided number of host per remote /// datacenter as failover for the local hosts. /// <p> /// The name of the local datacenter provided must be the local /// datacenter name as known by Cassandra.</p> ///</summary> /// <param name="localDc"> the name of the local datacenter (as known by /// Cassandra).</param> /// <param name="usedHostsPerRemoteDc"> the number of host per remote /// datacenter that policies created by the returned factory should /// consider. Created policies <c>distance</c> method will return a /// <c>HostDistance.Remote</c> distance for only <c> /// usedHostsPerRemoteDc</c> hosts per remote datacenter. Other hosts /// of the remote datacenters will be ignored (and thus no /// connections to them will be maintained).</param> public DCAwareRoundRobinPolicy(string localDc, int usedHostsPerRemoteDc) { _localDc = localDc; _usedHostsPerRemoteDc = usedHostsPerRemoteDc; } public void Initialize(ICluster cluster) { _cluster = cluster; //When the pool changes, it should clear the local cache _cluster.HostAdded += _ => ClearHosts(); _cluster.HostRemoved += _ => ClearHosts(); if (_localDc == null) { //Use the first host to determine the datacenter var firstHost = _cluster.AllHosts().FirstOrDefault(h => h.Datacenter != null); if (firstHost == null) { throw new DriverInternalError("Local datacenter could not be determined"); } _localDc = firstHost.Datacenter; } else { //Check that the datacenter exists if (_cluster.AllHosts().FirstOrDefault(h => h.Datacenter == _localDc) == null) { var availableDcs = String.Join(", ", _cluster.AllHosts().Select(h => h.Datacenter)); throw new ArgumentException(String.Format("Datacenter {0} does not match any of the nodes, available datacenters: {1}.", _localDc, availableDcs)); } } } /// <summary> /// Return the HostDistance for the provided host. <p> This policy consider nodes /// in the local datacenter as <c>Local</c>. For each remote datacenter, it /// considers a configurable number of hosts as <c>Remote</c> and the rest /// is <c>Ignored</c>. </p><p> To configure how many host in each remote /// datacenter is considered <c>Remote</c>.</p> /// </summary> /// <param name="host"> the host of which to return the distance of. </param> /// <returns>the HostDistance to <c>host</c>.</returns> public HostDistance Distance(Host host) { var dc = GetDatacenter(host); if (dc == _localDc) { return HostDistance.Local; } return HostDistance.Remote; } /// <summary> /// Returns the hosts to use for a new query. <p> The returned plan will always /// try each known host in the local datacenter first, and then, if none of the /// local host is reachable, will try up to a configurable number of other host /// per remote datacenter. The order of the local node in the returned query plan /// will follow a Round-robin algorithm.</p> /// </summary> /// <param name="keyspace">Keyspace on which the query is going to be executed</param> /// <param name="query"> the query for which to build the plan. </param> /// <returns>a new query plan, i.e. an iterator indicating which host to try /// first for querying, which one to use as failover, etc...</returns> public IEnumerable<Host> NewQueryPlan(string keyspace, IStatement query) { var startIndex = Interlocked.Increment(ref _index); //Simplified overflow protection if (startIndex > _maxIndex) { Interlocked.Exchange(ref _index, 0); } var hosts = GetHosts(); var localHosts = hosts.Item1; var remoteHosts = hosts.Item2; //Round-robin through local nodes for (var i = 0; i < localHosts.Count; i++) { yield return localHosts[(startIndex + i) % localHosts.Count]; } if (_usedHostsPerRemoteDc == 0) { yield break; } var dcHosts = new Dictionary<string, int>(); foreach (var h in remoteHosts) { int hostYieldedByDc; var dc = GetDatacenter(h); dcHosts.TryGetValue(dc, out hostYieldedByDc); if (hostYieldedByDc >= _usedHostsPerRemoteDc) { //We already returned the amount of remotes nodes required continue; } dcHosts[dc] = hostYieldedByDc + 1; yield return h; } } private void ClearHosts() { _hosts = null; } private string GetDatacenter(Host host) { var dc = host.Datacenter; return dc ?? _localDc; } /// <summary> /// Gets a tuple containing the list of local and remote nodes /// </summary> internal Tuple<List<Host>, List<Host>> GetHosts() { var hosts = _hosts; if (hosts != null) { return hosts; } lock (_hostCreationLock) { //Check that if it has been updated since we were waiting for the lock hosts = _hosts; if (hosts != null) { return hosts; } var localHosts = new List<Host>(); var remoteHosts = new List<Host>(); //Do not reorder instructions, the host list must be up to date now, not earlier Thread.MemoryBarrier(); //shallow copy the nodes var allNodes = _cluster.AllHosts().ToArray(); //Split between local and remote nodes foreach (var h in allNodes) { if (GetDatacenter(h) == _localDc) { localHosts.Add(h); } else if (_usedHostsPerRemoteDc > 0) { remoteHosts.Add(h); } } hosts = new Tuple<List<Host>, List<Host>>(localHosts, remoteHosts); _hosts = hosts; } return hosts; } } }