context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; namespace System.Diagnostics { public partial class Process { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { if (processName == null) { processName = string.Empty; } Process[] procs = GetProcesses(machineName); var list = new List<Process>(); for (int i = 0; i < procs.Length; i++) { if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) { list.Add(procs[i]); } else { procs[i].Dispose(); } } return list.ToArray(); } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { EnsureState(State.HaveId); Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId); return new TimeSpan(Convert.ToInt64(info.ri_system_time)); } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { // Get the RUsage data and convert the process start time (which is the number of // nanoseconds elapse from boot to that the process started) to seconds. EnsureState(State.HaveId); Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId); double seconds = info.ri_proc_start_abstime / NanoSecondToSecondFactor; // Convert timespan from boot to process start datetime. return BootTimeToDateTime(TimeSpan.FromSeconds(seconds)); } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { EnsureState(State.HaveId); Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId); return new TimeSpan(Convert.ToInt64(info.ri_system_time + info.ri_user_time)); } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { EnsureState(State.HaveId); Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId); return new TimeSpan(Convert.ToInt64(info.ri_user_time)); } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private unsafe IntPtr ProcessorAffinityCore { get { throw new PlatformNotSupportedException(SR.ProcessorAffinityNotSupported); } set { throw new PlatformNotSupportedException(SR.ProcessorAffinityNotSupported); } } /// <summary> /// Make sure we have obtained the min and max working set limits. /// </summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { // We can only do this for the current process on OS X if (_processId != Interop.Sys.GetPid()) throw new PlatformNotSupportedException(SR.OsxExternalProcessWorkingSetNotSupported); // Minimum working set (or resident set, as it is called on *nix) doesn't exist so set to 0 minWorkingSet = IntPtr.Zero; // Get the max working set size Interop.Sys.RLimit limit; if (Interop.Sys.GetRLimit(Interop.Sys.RlimitResources.RLIMIT_RSS, out limit) == 0) { maxWorkingSet = limit.CurrentLimit == Interop.Sys.RLIM_INFINITY ? new IntPtr(Int64.MaxValue) : new IntPtr(Convert.ToInt64(limit.CurrentLimit)); } else { // The contract specifies that this throws Win32Exception when it failes to retrieve the info throw new Win32Exception(); } } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { // We can only do this for the current process on OS X if (_processId != Interop.Sys.GetPid()) throw new PlatformNotSupportedException(SR.OsxExternalProcessWorkingSetNotSupported); // There isn't a way to set the minimum working set, so throw an exception here if (newMin.HasValue) { throw new PlatformNotSupportedException(SR.MinimumWorkingSetNotSupported); } // The minimum resident set will always be 0, default the resulting max to 0 until we set it (to make the compiler happy) resultingMin = IntPtr.Zero; resultingMax = IntPtr.Zero; // The default hard upper limit is absurdly high (over 9000PB) so just change the soft limit...especially since // if you aren't root and move the upper limit down, you need root to move it back up if (newMax.HasValue) { Interop.Sys.RLimit limits = new Interop.Sys.RLimit() { CurrentLimit = (ulong)newMax.Value.ToInt64() }; int result = Interop.Sys.SetRLimit(Interop.Sys.RlimitResources.RLIMIT_RSS, ref limits); if (result != 0) { throw new System.ComponentModel.Win32Exception(SR.RUsageFailure); } // Try to grab the actual value, in case the OS decides to fudge the numbers result = Interop.Sys.GetRLimit(Interop.Sys.RlimitResources.RLIMIT_RSS, out limits); if (result == 0) resultingMax = new IntPtr((long)limits.CurrentLimit); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary> private static string GetExePath() { return Interop.libproc.proc_pidpath(Interop.Sys.GetPid()); } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- // The ri_proc_start_abstime needs to be converted to seconds to determine // the actual start time of the process. private const int NanoSecondToSecondFactor = 1000000000; private Interop.libproc.rusage_info_v3 GetCurrentProcessRUsage() { return Interop.libproc.proc_pid_rusage(Interop.Sys.GetPid()); } } }
using System; using System.Collections.Generic; using System.Linq; namespace TfsCmdlets.Util { internal static class TfsVersionTable { internal static int GetYear(int majorVersion) { return _tfsMajorVersionTable[majorVersion]; } internal static int GetMajorVersion(int year) { return _tfsMajorVersionTable.Where(kvp => kvp.Value == year).Select(kvp => kvp.Key).First(); } internal static ServerVersion GetServerVersion(Version version) { if (!_tfsVersions.ContainsKey(version)) { return new ServerVersion { Version = version, FriendlyVersion = $"{(version.Major >= 17 ? "Azure DevOps" : "Team Foundation")} Server {GetYear(version.Major)}", IsHosted = false, LongVersion = $"{version} (TFS {TfsVersionTable.GetYear(version.Major)}))" }; } return _tfsVersions[version]; } internal static bool IsYear(int year) { return _tfsMajorVersionTable.ContainsValue(year); } internal static bool IsMajorVersion(int majorVersion) { return _tfsMajorVersionTable.ContainsKey(majorVersion); } private static readonly Dictionary<int, int> _tfsMajorVersionTable = new Dictionary<int, int> { [8] = 2005, [9] = 2008, [10] = 2010, [11] = 2011, [12] = 2013, [14] = 2015, [15] = 2017, [16] = 2018, [17] = 2019, [18] = 2020 }; private static readonly Dictionary<Version, ServerVersion> _tfsVersions = new Dictionary<Version, ServerVersion> { // TFS 2005 [new Version("8.0.50727.147")] = new ServerVersion() { Version = new Version("8.0.50727.147"), LongVersion = "8.0.50727.147 (TFS 2005 RTM)", FriendlyVersion = "Team Foundation Server 2005 (RTM)", Update = 0 }, [new Version("8.0.50727.762")] = new ServerVersion() { Version = new Version("8.0.50727.762"), LongVersion = "8.0.50727.762 (TFS 2005 SP1)", FriendlyVersion = "Team Foundation Server 2005 Service Pack 1", Update = 1 }, // TFS 2008 [new Version("9.0.21022.8")] = new ServerVersion() { Version = new Version("9.0.21022.8"), LongVersion = "9.0.21022.8 (TFS 2008 RTM)", FriendlyVersion = "Team Foundation Server 2008 (RTM)", Update = 0 }, [new Version("9.0.30729.1")] = new ServerVersion() { Version = new Version("9.0.30729.1"), LongVersion = "9.0.30729.1 (TFS 2008 SP1)", FriendlyVersion = "Team Foundation Server 2008 Service Pack 1", Update = 1 }, // TFS 2010 [new Version("10.0.30319.1")] = new ServerVersion() { Version = new Version("10.0.30319.1"), LongVersion = "10.0.30319.1 (TFS 2010 RTM)", FriendlyVersion = "Team Foundation Server 2010 (RTM)", Update = 0 }, [new Version("10.0.40219.1")] = new ServerVersion() { Version = new Version("10.0.40219.1"), LongVersion = "10.0.40219.1 (TFS 2010 SP1)", FriendlyVersion = "Team Foundation Server 2010 Service Pack 1", Update = 1 }, [new Version("10.0.40219.371")] = new ServerVersion() { Version = new Version("10.0.40219.371"), LongVersion = "10.0.40219.371 (TFS 2010 SP1 CU2)", FriendlyVersion = "Team Foundation Server 2010 Service Pack 1 Cumulative Update 2", Update = 1.2M }, // TFS 2012 [new Version("11.0.50727.1")] = new ServerVersion() { Version = new Version("11.0.50727.1"), LongVersion = "11.0.50727.1 (TFS 2012 RTM)", FriendlyVersion = "Team Foundation Server 2012 (RTM)", Update = 0 }, [new Version("11.0.51106.1")] = new ServerVersion() { Version = new Version("11.0.51106.1"), LongVersion = "11.0.51106.1 (TFS 2012.1)", FriendlyVersion = "Team Foundation Server 2012 Update 1", Update = 1 }, [new Version("11.0.60123.100")] = new ServerVersion() { Version = new Version("11.0.60123.100"), LongVersion = "11.0.60123.100 (TFS 2012.1.1)", FriendlyVersion = "Team Foundation Server 2012 Update 1 Cumulative Update 1", Update = 1.1M }, [new Version("11.0.60315.1")] = new ServerVersion() { Version = new Version("11.0.60315.1"), LongVersion = "11.0.60315.1 (TFS 2012.2)", FriendlyVersion = "Team Foundation Server 2012 Update 2", Update = 2 }, [new Version("11.0.60610.1")] = new ServerVersion() { Version = new Version("11.0.60610.1"), LongVersion = "11.0.60610.1 (TFS 2012.3)", FriendlyVersion = "Team Foundation Server 2012 Update 3", Update = 3 }, [new Version("11.0.61030.0")] = new ServerVersion() { Version = new Version("11.0.61030.0"), LongVersion = "11.0.61030.0 (TFS 2012.4)", FriendlyVersion = "Team Foundation Server 2012 Update 4", Update = 4 }, // TFS 2013 [new Version("12.0.20827.3")] = new ServerVersion() { Version = new Version("12.0.20827.3"), LongVersion = "12.0.20827.3 (TFS 2013 RC)", FriendlyVersion = "Team Foundation Server 2013 Release Candidate", Update = 0.9M }, [new Version("12.0.21005.1")] = new ServerVersion() { Version = new Version("12.0.21005.1"), LongVersion = "12.0.21005.1 (TFS 2013 RTM)", FriendlyVersion = "Team Foundation Server 2013 (RTM)", Update = 0 }, [new Version("12.0.30324.0")] = new ServerVersion() { Version = new Version("12.0.30324.0"), LongVersion = "12.0.30324.0 (TFS 2013.2)", FriendlyVersion = "Team Foundation Server 2013 Update 2", Update = 2 }, [new Version("12.0.30626.0")] = new ServerVersion() { Version = new Version("12.0.30626.0"), LongVersion = "12.0.30626.0 (TFS 2013.3 RC)", FriendlyVersion = "Team Foundation Server 2013 Update 3 Release Candidate", Update = 2.9M }, [new Version("12.0.30723.0")] = new ServerVersion() { Version = new Version("12.0.30723.0"), LongVersion = "12.0.30723.0 (TFS 2013.3)", FriendlyVersion = "Team Foundation Server 2013 Update 3", Update = 3 }, [new Version("12.0.31010.0")] = new ServerVersion() { Version = new Version("12.0.31010.0"), LongVersion = "12.0.31010.0 (TFS 2013.4 RC)", FriendlyVersion = "Team Foundation Server 2013 Update 4 Release Candidate", Update = 3.9M }, [new Version("12.0.31101.0")] = new ServerVersion() { Version = new Version("12.0.31101.0"), LongVersion = "12.0.31101.0 (TFS 2013.4)", FriendlyVersion = "Team Foundation Server 2013 Update 4", Update = 4 }, [new Version("12.0.40629.0")] = new ServerVersion() { Version = new Version("12.0.40629.0"), LongVersion = "12.0.40629.0 (TFS 2013.5)", FriendlyVersion = "Team Foundation Server 2013 Update 5", Update = 5 }, // TFS 2015 // TFS 2017 // TFS 2018 [new Version("16.121.26818.0")] = new ServerVersion() { Version = new Version("16.121.26818.0"), LongVersion = "16.121.26818.0 (TFS 2018 RC1)", FriendlyVersion = "Team Foundation Server 2018 Release Candidate 1", Update = 0.91M }, [new Version("16.122.26918.3")] = new ServerVersion() { Version = new Version("16.122.26918.3"), LongVersion = "16.122.26918.3 (TFS 2018 RC2)", FriendlyVersion = "Team Foundation Server 2018 Release Candidate 2", Update = 0.92M }, [new Version("16.122.27102.1")] = new ServerVersion() { Version = new Version("16.122.27102.1"), LongVersion = "16.122.27102.1 (TFS 2018 RTW)", FriendlyVersion = "Team Foundation Server 2018 (RTW)", Update = 0 }, // TFS (Azure DevOps Server) 2019 // TFS (Azure DevOps Server) 2020 }; } /// <summary> /// Represents the version of a Team Foundation / Azure DevOps Server installation, and/or /// the currently deployed version of Azure DevOps in an Azure DevOps Services organization /// </summary> public class ServerVersion { /// <summary> /// Gets the "four-part" version of TFS / Azure DevOps /// </summary> public Version Version { get; set; } /// <summary> /// Gets the "long" version of TFS / Azure DevOps /// </summary> public string LongVersion { get; set; } /// <summary> /// Gets the "friendly" version of TFS / Azure DevOps /// </summary> public string FriendlyVersion { get; set; } /// <summary> /// Indicates whether it's a "hosted" (Azure DevOps Services) deployment or not /// (TFS/Azure DevOps Server) /// </summary> public bool IsHosted { get; set; } /// <summary> /// Gets the version number of the Update installed on a server, or number of the sprint /// currently deployed in an Azure DevOps Services organization /// </summary> public decimal Update { get; set; } /// <summary> /// Gets the version of the server as its corresponding year (e.g. 2019 for version 17.*) /// </summary> public int YearVersion => TfsVersionTable.GetYear(Version.Major); } }
// 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.Globalization; using Xunit; public static class CharTests { [Theory] [InlineData('h', 'h', 0)] [InlineData('h', 'a', 1)] [InlineData('h', 'z', -1)] [InlineData('h', null, 1)] public static void TestCompareTo(char c, object value, int expected) { if (value is char) { Assert.Equal(expected, Math.Sign(c.CompareTo((char)value))); } IComparable comparable = c; Assert.Equal(expected, Math.Sign(comparable.CompareTo(value))); } [Fact] public static void TestCompareTo_Invalid() { IComparable comparable = 'h'; Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("H")); // Value not a char } [Fact] public static void TestConvertFromUtf32_InvalidChar() { // TODO: add this as [InlineData] when #7166 is fixed TestConvertFromUtf32(0xFFFF, "\uFFFF"); } [Theory] [InlineData(0x10000, "\uD800\uDC00")] [InlineData(0x103FF, "\uD800\uDFFF")] [InlineData(0xFFFFF, "\uDBBF\uDFFF")] [InlineData(0x10FC00, "\uDBFF\uDC00")] [InlineData(0x10FFFF, "\uDBFF\uDFFF")] [InlineData(0, "\0")] [InlineData(0x3FF, "\u03FF")] [InlineData(0xE000, "\uE000")] public static void TestConvertFromUtf32(int utf32, string expected) { // TODO: add this as [InlineData] when #7166 is fixed Assert.Equal(expected, char.ConvertFromUtf32(utf32)); } [Theory] [InlineData(0xD800)] [InlineData(0xDC00)] [InlineData(0xDFFF)] [InlineData(0x110000)] [InlineData(-1)] [InlineData(int.MaxValue)] [InlineData(int.MinValue)] public static void TestConvertFromUtf32_Invalid(int utf32) { Assert.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32)); } [Fact] public static void TestConvertToUtf32_String_Int() { // TODO: add this as [InlineData] when #7166 is fixed TestConvertToUtf32_String_Int("\uD800\uD800\uDFFF", 1, 0x103FF); TestConvertToUtf32_String_Int("\uD800\uD7FF", 1, 0xD7FF); // High, non-surrogate TestConvertToUtf32_String_Int("\uD800\u0000", 1, 0); // High, non-surrogate TestConvertToUtf32_String_Int("\uDF01\u0000", 1, 0); // Low, non-surrogate } [Theory] [InlineData("\uD800\uDC00", 0, 0x10000)] [InlineData("\uDBBF\uDFFF", 0, 0xFFFFF)] [InlineData("\uDBBF\uDFFF", 0, 0xFFFFF)] [InlineData("\uDBFF\uDC00", 0, 0x10FC00)] [InlineData("\uDBFF\uDFFF", 0, 0x10FFFF)] [InlineData("\u0000\u0001", 0, 0)] [InlineData("\u0000\u0001", 1, 1)] [InlineData("\u0000", 0, 0)] [InlineData("\u0020\uD7FF", 0, 32)] [InlineData("\u0020\uD7FF", 1, 0xD7FF)] [InlineData("abcde", 4, 'e')] public static void TestConvertToUtf32_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.ConvertToUtf32(s, index)); } [Fact] public static void TestConvertToUtf32_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length } [Fact] public static void TestConvertToUtf32_Char_Char() { // TODO: add this as [InlineData] when #7166 is fixed TestConvertToUtf32_Char_Char('\uD800', '\uDC00', 0x10000); TestConvertToUtf32_Char_Char('\uD800', '\uDC00', 0x10000); TestConvertToUtf32_Char_Char('\uD800', '\uDFFF', 0x103FF); TestConvertToUtf32_Char_Char('\uDBBF', '\uDFFF', 0xFFFFF); TestConvertToUtf32_Char_Char('\uDBFF', '\uDC00', 0x10FC00); TestConvertToUtf32_Char_Char('\uDBFF', '\uDFFF', 0x10FFFF); } private static void TestConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected) { Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate)); } [Fact] public static void TestConvertToUtf32_Char_Char_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate } [Theory] [InlineData('a', 'a', true)] [InlineData('a', 'A', false)] [InlineData('a', 'b', false)] [InlineData('a', (int)'a', false)] [InlineData('a', "a", false)] [InlineData('a', null, false)] public static void TestEquals(char c, object obj, bool expected) { if (obj is char) { Assert.Equal(expected, c.Equals((char)obj)); Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode())); } Assert.Equal(expected, c.Equals(obj)); } [Theory] [InlineData('0', 0)] [InlineData('9', 9)] [InlineData('T', -1)] public static void TestGetNumericValue_Char(char c, int expected) { Assert.Equal(expected, char.GetNumericValue(c)); } [Theory] [InlineData("\uD800\uDD07", 0, 1)] [InlineData("9", 0, 9)] [InlineData("99", 1, 9)] [InlineData(" 7 ", 1, 7)] [InlineData("Test 7", 5, 7)] [InlineData("T", 0, -1)] public static void TestGetNumericValue_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.GetNumericValue(s, index)); } [Fact] public static void TestGetNumericValue_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsControl_Char() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c)); } [Fact] public static void TestIsControl_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c.ToString(), 0)); } [Fact] public static void TestIsControl_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsDigit_Char() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsDigit_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c.ToString(), 0)); } [Fact] public static void TestIsDigit_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetter_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetter_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c.ToString(), 0)); } [Fact] public static void TestIsLetter_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetterOrDigit_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetterOrDigit_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c.ToString(), 0)); } [Fact] public static void TestIsLetterOrDigit_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLower_Char() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLower_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c.ToString(), 0)); } [Fact] public static void TestIsLower_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsNumber_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsNumber_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c.ToString(), 0)); } [Fact] public static void TestIsNumber_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsPunctuation_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c)); } [Fact] public static void TestIsPunctuation_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c.ToString(), 0)); } [Fact] public static void TestIsPunctuation_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsSeparator_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c)); } [Fact] public static void TestIsSeparator_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c.ToString(), 0)); } [Fact] public static void TestIsSeparator_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsLowSurrogate_Char() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c)); } [Fact] public static void TestIsLowSurrogate_String_Int() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); } [Fact] public static void TestIsLowSurrogate_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsHighSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c)); } [Fact] public static void TestIsHighSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); } [Fact] public static void TestIsHighSurrogate_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c)); } [Fact] public static void TestIsSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c.ToString(), 0)); } [Fact] public static void TestIsSurrogate_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsSurrogatePair_Char() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); } [Fact] public static void TestIsSurrogatePair_String_Int() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length } [Fact] public static void TestIsSurrogatePair_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsSymbol_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c)); } [Fact] public static void TestIsSymbol_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c.ToString(), 0)); } [Fact] public static void TestIsSymbol_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsUpper_Char() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c)); } [Fact] public static void TestIsUpper_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c.ToString(), 0)); } [Fact] public static void TestIsUpper_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length } [Fact] public static void TestIsWhitespace_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c)); } } [Fact] public static void TestIsWhiteSpace_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c.ToString(), 0)); // Some control chars are also considered whitespace for legacy reasons. // if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace("\u000b", 0)); Assert.True(char.IsWhiteSpace("\u0085", 0)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c.ToString(), 0)); } } [Fact] public static void TestIsWhiteSpace_String_Int_Invalid() { Assert.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length } [Fact] public static void TestMaxValue() { Assert.Equal(0xffff, char.MaxValue); } [Fact] public static void TestMinValue() { Assert.Equal(0, char.MinValue); } [Fact] public static void TestToLower() { Assert.Equal('a', char.ToLower('A')); Assert.Equal('a', char.ToLower('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLower(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLower(c)); } } [Fact] public static void TestToLowerInvariant() { Assert.Equal('a', char.ToLowerInvariant('A')); Assert.Equal('a', char.ToLowerInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLowerInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLowerInvariant(c)); } } [Theory] [InlineData('a', "a")] [InlineData('\uabcd', "\uabcd")] public static void TestToString(char c, string expected) { Assert.Equal(expected, c.ToString()); Assert.Equal(expected, char.ToString(c)); } [Fact] public static void TestToUpper() { Assert.Equal('A', char.ToUpper('A')); Assert.Equal('A', char.ToUpper('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpper(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpper(c)); } } [Fact] public static void TestToUpperInvariant() { Assert.Equal('A', char.ToUpperInvariant('A')); Assert.Equal('A', char.ToUpperInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpperInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpperInvariant(c)); } } [Theory] [InlineData("a", 'a')] [InlineData("4", '4')] [InlineData(" ", ' ')] [InlineData("\n", '\n')] [InlineData("\0", '\0')] [InlineData("\u0135", '\u0135')] [InlineData("\u05d9", '\u05d9')] [InlineData("\ue001", '\ue001')] // Private use codepoint public static void TestParse(string s, char expected) { char c; Assert.True(char.TryParse(s, out c)); Assert.Equal(expected, c); Assert.Equal(expected, char.Parse(s)); } [Fact] public static void TestParse_Surrogate() { // TODO: add this as [InlineData] when #7166 is fixed TestParse("\ud801", '\ud801'); // High surrogate TestParse("\udc01", '\udc01'); // Low surrogate } [Theory] [InlineData(null, typeof(ArgumentNullException))] [InlineData("", typeof(FormatException))] [InlineData("\n\r", typeof(FormatException))] [InlineData("kj", typeof(FormatException))] [InlineData(" a", typeof(FormatException))] [InlineData("a ", typeof(FormatException))] [InlineData("\\u0135", typeof(FormatException))] [InlineData("\u01356", typeof(FormatException))] [InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair public static void TestParse_Invalid(string s, Type exceptionType) { char c; Assert.False(char.TryParse(s, out c)); Assert.Equal(default(char), c); Assert.Throws(exceptionType, () => char.Parse(s)); } private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories) { Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length); for (int i = 0; i < s_latinTestSet.Length; i++) { if (Array.Exists(categories, uc => uc == (UnicodeCategory)i)) continue; char[] latinSet = s_latinTestSet[i]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[i]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories) { for (int i = 0; i < categories.Length; i++) { char[] latinSet = s_latinTestSet[(int)categories[i]]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[(int)categories[i]]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static char[][] s_latinTestSet = new char[][] { new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter new char[] {}, // UnicodeCategory.TitlecaseLetter new char[] {}, // UnicodeCategory.ModifierLetter new char[] {}, // UnicodeCategory.OtherLetter new char[] {}, // UnicodeCategory.NonSpacingMark new char[] {}, // UnicodeCategory.SpacingCombiningMark new char[] {}, // UnicodeCategory.EnclosingMark new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber new char[] {}, // UnicodeCategory.LetterNumber new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator new char[] {}, // UnicodeCategory.LineSeparator new char[] {}, // UnicodeCategory.ParagraphSeparator new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control new char[] {}, // UnicodeCategory.Format new char[] {}, // UnicodeCategory.Surrogate new char[] {}, // UnicodeCategory.PrivateUse new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol new char[] {}, // UnicodeCategory.OtherNotAssigned }; private static char[][] s_unicodeTestSet = new char[][] { new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator new char[] {'\u2028'}, // UnicodeCategory.LineSeparator new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator new char[] {}, // UnicodeCategory.Control new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol new char[] {'\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned }; private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff' private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff' private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' }; }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Rainbow.Framework.Providers.RainbowMembershipProvider; using System.Collections.Specialized; using System.Web.Security; using System.Data.SqlClient; namespace Rainbow.Tests { [TestFixture] public class MembershipProviderTest { [TestFixtureSetUp] public void FixtureSetUp() { // Set up initial database environment for testing purposes TestHelper.TearDownDB(); TestHelper.RecreateDBSchema(); } [Test] public void Foo() { Console.WriteLine( "This should pass. It only writes to the Console." ); } #region Config properties [Test] public void ApplicationNameTest() { try { string appName = Membership.ApplicationName; Assert.AreEqual( appName, "Rainbow" ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving ApplicationName property", ex ); } } [Test] public void EnablePasswordResetTest() { try { bool enablePwdReset = Membership.EnablePasswordReset; Assert.AreEqual( enablePwdReset, true ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving EnablePasswordReset property", ex ); } } [Test] public void EnablePasswordRetrievalTest() { try { bool enablePwdRetrieval = Membership.EnablePasswordRetrieval; Assert.AreEqual( enablePwdRetrieval, false ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving EnablePasswordRetrieval property", ex ); } } [Test] public void HashAlgorithmTypeTest() { try { string hashAlgType = Membership.HashAlgorithmType; Assert.AreEqual( hashAlgType, "SHA1" ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving HashAlgorithmType property", ex ); } } [Test] public void MaxInvalidPasswordAttemptsTest() { try { int maxInvalidPwdAttempts = Membership.MaxInvalidPasswordAttempts; Assert.AreEqual( maxInvalidPwdAttempts, 5 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving MaxInvalidPasswordAttempts property", ex ); } } [Test] public void MinRequiredNonAlphanumericCharactersTest() { try { int minReqNonAlpha = Membership.MinRequiredNonAlphanumericCharacters; Assert.AreEqual( minReqNonAlpha, 1 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving MinRequiredNonAlphanumericCharacters property", ex ); } } [Test] public void MinRequiredPasswordLengthTest() { try { int minReqPwdLength = Membership.MinRequiredPasswordLength; Assert.AreEqual( minReqPwdLength, 5 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving MinRequiredPasswordLength property", ex ); } } [Test] public void PasswordAttemptWindowTest() { try { int pwdAttemptWindow = Membership.PasswordAttemptWindow; Assert.AreEqual( pwdAttemptWindow, 15 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving PasswordAttemptWindows property", ex ); } } [Test] public void PasswordStrengthRegularExpressionTest() { try { string pwdStrengthRegex = Membership.PasswordStrengthRegularExpression; Assert.AreEqual( pwdStrengthRegex, string.Empty ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving PasswordStrengthRegularExpression property", ex ); } } [Test] public void ProviderTest() { try { MembershipProvider provider = Membership.Provider; Assert.AreEqual( provider.GetType(), typeof( Rainbow.Framework.Providers.RainbowMembershipProvider.RainbowSqlMembershipProvider ) ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving Provider property", ex ); } } [Test] public void ProvidersTest() { try { MembershipProviderCollection providers = Membership.Providers; Assert.AreEqual( providers.Count, 1 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving Providers property", ex ); } } [Test] public void RequiresQuestionAndAnswerTest() { try { bool reqQuestionAndAnswer = Membership.RequiresQuestionAndAnswer; Assert.AreEqual( reqQuestionAndAnswer, false ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error retrieving RequiresQuestionAndAnswer property", ex ); } } #endregion #region Membership provider methods [Test] public void GetAllUsersTest() { try { int totalRecords; Membership.GetAllUsers(); Membership.GetAllUsers( 0, 1, out totalRecords ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetAllUsersTest", ex ); } } [Test] public void GetNumberOfUsersOnlineTest() { try { Membership.GetNumberOfUsersOnline(); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetNumberOfUsersOnlineTest", ex ); } } [Test] public void GetPasswordTest() { try { if ( Membership.EnablePasswordRetrieval ) { string pwd = Membership.Provider.GetPassword( "admin@rainbowportal.net", "answer" ); } } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetPasswordTest", ex ); } } [Test] public void GetUserTest() { try { MembershipUser user = Membership.GetUser( "admin@rainbowportal.net" ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetUserTest", ex ); } } [Test] public void GetUserNameByEmailValidUserTest() { try { string userName = Membership.GetUserNameByEmail( "admin@rainbowportal.net" ); Assert.AreEqual( userName, "admin@rainbowportal.net" ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetUserNameByEmailValidUserTest", ex ); } } [Test] public void GetUserNameByEmailInvalidUserTest() { try { string userName = Membership.GetUserNameByEmail( "invaliduser@doesnotexist.com" ); Assert.AreEqual( userName, string.Empty ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in GetUserNameByEmailInvalidUserTest", ex ); } } [Test] public void FindUsersByNameTest1() { try { MembershipUserCollection users = Membership.FindUsersByName( "admin@rainbowportal.net" ); Assert.AreEqual( users.Count, 1 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByNameTest1", ex ); } } [Test] public void FindUsersByNameTest2() { try { MembershipUserCollection users = Membership.FindUsersByName( "invaliduser@doesnotexist.com" ); Assert.IsEmpty( users ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByNameTest2", ex ); } } [Test] public void FindUsersByNameTest3() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByName( "admin@rainbowportal.net", 0, 10, out totalRecords ); Assert.AreEqual( users.Count, 1 ); Assert.Greater( totalRecords, 0 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByNameTest3", ex ); } } [Test] public void FindUsersByNameTest4() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByName( "invaliduser@doesnotexist.com", 0, 10, out totalRecords ); Assert.IsEmpty( users ); Assert.AreEqual( totalRecords, 0 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByNameTest4", ex ); } } [Test] public void FindUsersByEmailTest1() { try { MembershipUserCollection users = Membership.FindUsersByEmail( "admin@rainbowportal.net" ); Assert.AreEqual( users.Count, 1 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByEmailTest1", ex ); } } [Test] public void FindUsersByEmailTest2() { try { MembershipUserCollection users = Membership.FindUsersByName( "invaliduser@doesnotexist.com" ); Assert.IsEmpty( users ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByEmailTest2", ex ); } } [Test] public void FindUsersByEmailTest3() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByEmail( "admin@rainbowportal.net", 0, 10, out totalRecords ); Assert.AreEqual( users.Count, 1 ); Assert.Greater( totalRecords, 0 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByEmailTest3", ex ); } } [Test] public void FindUsersByEmailTest4() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByEmail( "invaliduser@doesnotexist.com", 0, 10, out totalRecords ); Assert.IsEmpty( users ); Assert.AreEqual( totalRecords, 0 ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in FindUsersByEmailTes4", ex ); } } [Test] public void ValidateUserTest1() { try { bool isValid = Membership.ValidateUser( "admin@rainbowportal.net", "notavalidpwd" ); Assert.IsFalse( isValid ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ValidateUserTest1", ex ); } } [Test] public void ValidateUserTest2() { try { bool isValid = Membership.ValidateUser( "admin@rainbowportal.net", "admin" ); Assert.IsTrue( isValid ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ValidateUserTest2", ex ); } } [Test] public void ValidateUserTest3() { try { bool isValid = Membership.ValidateUser( "invaliduser@doesnotexist.com", "notavalidpwd" ); Assert.IsFalse( isValid ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ValidateUserTest3", ex ); } } [Test] public void ValidateUserTest4() { try { bool isValid = Membership.ValidateUser( "invaliduser@doesnotexist.com", "admin" ); Assert.IsFalse( isValid ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ValidateUserTest4", ex ); } } [Test] public void ChangePasswordQuestionAndAnswerTest1() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer( "admin@rainbowportal.net", "admin", "newPasswordQuestion", "newPasswordAnswer"); Assert.IsTrue( pwdChanged ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordQuestionAndAnswer1", ex ); } } [Test] public void ChangePasswordQuestionAndAnswerTest2() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer( "admin@rainbowportal.net", "invalidPwd", "newPasswordQuestion", "newPasswordAnswer" ); Assert.IsFalse( pwdChanged ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordQuestionAndAnswer2", ex ); } } [Test] public void ChangePasswordQuestionAndAnswerTest3() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer( "invaliduser@doesnotexist.com", "InvalidPwd", "newPasswordQuestion", "newPasswordAnswer" ); Assert.IsFalse( pwdChanged ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordQuestionAndAnswer3", ex ); } } [Test] public void UnlockUserTest1() { try { bool unlocked = Membership.Provider.UnlockUser( "admin@rainbowportal.net" ); Assert.IsTrue( unlocked ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in UnlockUserTest1", ex ); } } [Test] public void UnlockUserTest2() { try { bool unlocked = Membership.Provider.UnlockUser( "invaliduser@doesnotexist.com" ); Assert.IsFalse( unlocked ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in UnlockUserTest2", ex ); } } [Test] public void CreateUserTest1() { try { MembershipCreateStatus status; MembershipUser user = Membership.CreateUser( "Admin@rainbowportal.net", "admin", "Admin@rainbowportal.net", "question", "answer", true, out status); Assert.IsNull( user ); Assert.AreEqual( status, MembershipCreateStatus.DuplicateUserName ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in CreateUserTest1", ex ); } } [Test] public void CreateUserTest2() { try { MembershipCreateStatus status; MembershipUser user = Membership.CreateUser( "Tito", "tito", "tito@tito.com", "question", "answer", true, out status ); Assert.IsNotNull( user ); Assert.AreEqual( status, MembershipCreateStatus.Success ); Assert.AreEqual( user.UserName, "Tito" ); Assert.AreEqual( user.Email, "tito@tito.com" ); Assert.AreEqual( user.PasswordQuestion, "question" ); Assert.IsTrue( user.IsApproved ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in CreateUserTest2", ex ); } } [Test] public void ChangePasswordTest1() { try { bool sucess = Membership.Provider.ChangePassword( "Tito", "tito", "newPassword" ); Assert.IsTrue( sucess ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordTest1", ex ); } } [Test] public void ChangePasswordTest2() { try { bool sucess = Membership.Provider.ChangePassword( "invaliduser@doesnotexist.com", "pwd", "newPassword" ); Assert.IsFalse( sucess ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordTest2", ex ); } } [Test] public void ChangePasswordTest3() { try { bool sucess = Membership.Provider.ChangePassword( "Admin@rainbowportal.net", "invalidPwd", "newPassword" ); Assert.IsFalse( sucess ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ChangePasswordTest3", ex ); } } [Test] public void UpdateUserTest1() { try { RainbowUser user = ( RainbowUser )Membership.GetUser( "Tito" ); Assert.AreEqual( user.Email, "tito@tito.com" ); Assert.IsTrue( user.IsApproved ); user.Email = "newEmail@tito.com"; user.IsApproved = false; user.LastLoginDate = new DateTime( 1982, 2, 6 ); Membership.UpdateUser( user ); user = ( RainbowUser )Membership.GetUser( "Tito" ); Assert.AreEqual( user.Email, "newEmail@tito.com" ); Assert.IsFalse( user.IsApproved ); Assert.AreEqual( new DateTime( 1982, 2, 6 ), user.LastLoginDate ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in UpdateUserTest1", ex ); } } [Test] public void UpdateUserTest2() { try { RainbowUser user = new RainbowUser( Membership.Provider.Name, "invalidUserName", Guid.NewGuid(), "tito@tito.com", "question", "answer", true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MinValue ); Membership.UpdateUser( user ); Assert.Fail( "UpdateUser didn't throw an exception even though userName was invalid" ); } catch ( RainbowMembershipProviderException ) { } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in UpdateUserTest1", ex ); } } [Test] public void ResetPasswordTest1() { try { string newPwd = Membership.Provider.ResetPassword( "invalidUser", "answer" ); Assert.Fail( "ResetPassword went ok with invalid user name" ); } catch ( RainbowMembershipProviderException ) { } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ResetPasswordTest1", ex ); } } [Test] public void ResetPasswordTest2() { try { string newPwd = Membership.Provider.ResetPassword( "Tito", "invalidAnswer" ); Assert.Fail( "ResetPassword went ok with invalid password answer" ); } catch ( MembershipPasswordException ) { } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ResetPasswordTest2", ex ); } } [Test] public void ResetPasswordTest3() { try { string newPwd = Membership.Provider.ResetPassword( "Tito", "answer" ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in ResetPasswordTest3", ex ); } } [Test] public void DeleteUserTest1() { try { bool success = Membership.DeleteUser( "invalidUser" ); Assert.IsFalse( success ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in DeleteUserTest1", ex ); } } [Test] public void DeleteUserTest2() { try { bool success = Membership.DeleteUser( "Tito" ); Assert.IsTrue( success ); } catch ( Exception ex ) { Console.WriteLine( ex.Message + ex.StackTrace ); Assert.Fail( "Error in DeleteUserTest2", ex ); } } #endregion } }
/* * * (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. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using MIME; #endregion /// <summary> /// This class represents <b>address-list</b>. Defined in RFC 5322 3.4. /// </summary> public class Mail_t_AddressList : IEnumerable { #region Members private readonly List<Mail_t_Address> m_pList; private bool m_IsModified; private static System.Text.RegularExpressions.Regex m_regParser = new System.Text.RegularExpressions.Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" + "@" + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");//"^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"); #endregion #region Properties /// <summary> /// Gets if list has modified since it was loaded. /// </summary> public bool IsModified { get { return m_IsModified; } } /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pList.Count; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>Returns the element at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> public Mail_t_Address this[int index] { get { if (index < 0 || index >= m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } return m_pList[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Mail_t_AddressList() { m_pList = new List<Mail_t_Address>(); } #endregion #region Methods /// <summary> /// Inserts a address into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the item.</param> /// <param name="value">Address to insert.</param> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public void Insert(int index, Mail_t_Address value) { if (index < 0 || index > m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } if (value == null) { throw new ArgumentNullException("value"); } m_pList.Insert(index, value); m_IsModified = true; } /// <summary> /// Adds specified address to the end of the collection. /// </summary> /// <param name="value">Address to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Add(Mail_t_Address value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Add(value); m_IsModified = true; } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="value">Address to remove.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Remove(Mail_t_Address value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Remove(value); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { m_pList.Clear(); m_IsModified = true; } /// <summary> /// Copies addresses to new array. /// </summary> /// <returns>Returns addresses array.</returns> public Mail_t_Address[] ToArray() { return m_pList.ToArray(); } /// <summary> /// Returns address-list as string. /// </summary> /// <returns>Returns address-list as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < m_pList.Count; i++) { if (i == (m_pList.Count - 1)) { retVal.Append(m_pList[i].ToString()); } else { retVal.Append(m_pList[i] + ","); } } return retVal.ToString(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pList.GetEnumerator(); } #endregion #region Internal methods /// <summary> /// Resets IsModified property to false. /// </summary> internal void AcceptChanges() { m_IsModified = false; } #endregion public static Mail_t_AddressList ParseAddressList(string value) { MIME_Reader r = new MIME_Reader(value); /* RFC 5322 3.4. address = mailbox / group mailbox = name-addr / addr-spec name-addr = [display-name] angle-addr angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr group = display-name ":" [group-list] ";" [CFWS] display-name = phrase mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list address-list = (address *("," address)) / obs-addr-list group-list = mailbox-list / CFWS / obs-group-list */ Mail_t_AddressList retVal = new Mail_t_AddressList(); while (true) { string word = r.QuotedReadToDelimiter(new[] { ',', '<', ':' }); // We processed all data. if (word == null && r.Available == 0) { if (retVal.Count == 0) { if (CheckEmail(value)) { retVal.Add(new Mail_t_Mailbox(null, value)); } } break; } // skip old group address format else if (r.Peek(true) == ':') { // Consume ':' r.Char(true); } // name-addr else if (r.Peek(true) == '<') { string address = r.ReadParenthesized(); if (CheckEmail(address)) { retVal.Add( new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeS(TextUtils.UnQuoteString(word)) : null, address)); } } // addr-spec else { if (CheckEmail(word)) { retVal.Add(new Mail_t_Mailbox(null, word)); } } // We have more addresses. if (r.Peek(true) == ',') { r.Char(false); } } return retVal; } private static bool CheckEmail(string EmailAddress) { return !string.IsNullOrEmpty(EmailAddress) ? m_regParser.IsMatch(EmailAddress.Trim()) : false; } } }
// 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; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using System.Collections.Generic; using Microsoft.Build.Shared.FileSystem; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using ProjectItemInstanceFactory = Microsoft.Build.Execution.ProjectItemInstance.TaskItem.ProjectItemInstanceFactory; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { public class BatchingEngine_Tests { [Fact] public void GetBuckets() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); List<string> parameters = new List<string>(); parameters.Add("@(File);$(unittests)"); parameters.Add("$(obj)\\%(Filename).ext"); parameters.Add("@(File->'%(extension)')"); // attributes in transforms don't affect batching ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); IList<ProjectItemInstance> items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "File", "a.foo", project.FullPath)); items.Add(new ProjectItemInstance(project, "File", "b.foo", project.FullPath)); items.Add(new ProjectItemInstance(project, "File", "c.foo", project.FullPath)); items.Add(new ProjectItemInstance(project, "File", "d.foo", project.FullPath)); items.Add(new ProjectItemInstance(project, "File", "e.foo", project.FullPath)); itemsByType.ImportItems(items); items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "Doc", "a.doc", project.FullPath)); items.Add(new ProjectItemInstance(project, "Doc", "b.doc", project.FullPath)); items.Add(new ProjectItemInstance(project, "Doc", "c.doc", project.FullPath)); items.Add(new ProjectItemInstance(project, "Doc", "d.doc", project.FullPath)); items.Add(new ProjectItemInstance(project, "Doc", "e.doc", project.FullPath)); itemsByType.ImportItems(items); PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); properties.Set(ProjectPropertyInstance.Create("UnitTests", "unittests.foo")); properties.Set(ProjectPropertyInstance.Create("OBJ", "obj")); List<ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance); Assert.Equal(5, buckets.Count); foreach (ItemBucket bucket in buckets) { // non-batching data -- same for all buckets XmlAttribute tempXmlAttribute = (new XmlDocument()).CreateAttribute("attrib"); tempXmlAttribute.Value = "'$(Obj)'=='obj'"; Assert.True(ConditionEvaluator.EvaluateCondition(tempXmlAttribute.Value, ParserOptions.AllowAll, bucket.Expander, ExpanderOptions.ExpandAll, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4), FileSystems.Default)); Assert.Equal("a.doc;b.doc;c.doc;d.doc;e.doc", bucket.Expander.ExpandIntoStringAndUnescape("@(doc)", ExpanderOptions.ExpandItems, MockElementLocation.Instance)); Assert.Equal("unittests.foo", bucket.Expander.ExpandIntoStringAndUnescape("$(bogus)$(UNITTESTS)", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance)); } Assert.Equal("a.foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File)", ExpanderOptions.ExpandItems, MockElementLocation.Instance)); Assert.Equal(".foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File->'%(Extension)')", ExpanderOptions.ExpandItems, MockElementLocation.Instance)); Assert.Equal("obj\\a.ext", buckets[0].Expander.ExpandIntoStringAndUnescape("$(obj)\\%(Filename).ext", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance)); // we weren't batching on this attribute, so it has no value Assert.Equal(String.Empty, buckets[0].Expander.ExpandIntoStringAndUnescape("%(Extension)", ExpanderOptions.ExpandAll, MockElementLocation.Instance)); ProjectItemInstanceFactory factory = new ProjectItemInstanceFactory(project, "i"); items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file)", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.NotNull(items); Assert.Single(items); int invalidProjectFileExceptions = 0; try { // This should throw because we don't allow item lists to be concatenated // with other strings. bool throwAway; items = buckets[0].Expander.ExpandSingleItemVectorExpressionIntoItems("@(file)$(unitests)", factory, ExpanderOptions.ExpandItems, false /* no nulls */, out throwAway, MockElementLocation.Instance); } catch (InvalidProjectFileException ex) { // check we don't lose error codes from IPFE's during build Assert.Equal("MSB4012", ex.ErrorCode); invalidProjectFileExceptions++; } // We do allow separators in item vectors, this results in an item group with a single flattened item items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file, ',')", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.NotNull(items); Assert.Single(items); Assert.Equal("a.foo", items[0].EvaluatedInclude); Assert.Equal(1, invalidProjectFileExceptions); } /// <summary> /// Tests the real simple case of using an unqualified metadata reference %(Culture), /// where there are only two items and both of them have a value for Culture, but they /// have different values. /// </summary> [Fact] public void ValidUnqualifiedMetadataReference() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); List<string> parameters = new List<string>(); parameters.Add("@(File)"); parameters.Add("%(Culture)"); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); List<ProjectItemInstance> items = new List<ProjectItemInstance>(); ProjectItemInstance a = new ProjectItemInstance(project, "File", "a.foo", project.FullPath); ProjectItemInstance b = new ProjectItemInstance(project, "File", "b.foo", project.FullPath); a.SetMetadata("Culture", "fr-fr"); b.SetMetadata("Culture", "en-en"); items.Add(a); items.Add(b); itemsByType.ImportItems(items); PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); List<ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), null); Assert.Equal(2, buckets.Count); } /// <summary> /// Tests the case where an unqualified metadata reference is used illegally. /// It's illegal because not all of the items consumed contain a value for /// that metadata. /// </summary> [Fact] public void InvalidUnqualifiedMetadataReference() { Assert.Throws<InvalidProjectFileException>(() => { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); List<string> parameters = new List<string>(); parameters.Add("@(File)"); parameters.Add("%(Culture)"); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); List<ProjectItemInstance> items = new List<ProjectItemInstance>(); ProjectItemInstance a = new ProjectItemInstance(project, "File", "a.foo", project.FullPath); items.Add(a); ProjectItemInstance b = new ProjectItemInstance(project, "File", "b.foo", project.FullPath); items.Add(b); a.SetMetadata("Culture", "fr-fr"); itemsByType.ImportItems(items); PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); // This is expected to throw because not all items contain a value for metadata "Culture". // Only a.foo has a Culture metadata. b.foo does not. BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance); } ); } /// <summary> /// Tests the case where an unqualified metadata reference is used illegally. /// It's illegal because not all of the items consumed contain a value for /// that metadata. /// </summary> [Fact] public void NoItemsConsumed() { Assert.Throws<InvalidProjectFileException>(() => { List<string> parameters = new List<string>(); parameters.Add("$(File)"); parameters.Add("%(Culture)"); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); // This is expected to throw because we have no idea what item list %(Culture) refers to. BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance); } ); } /// <summary> /// Missing unittest found by mutation testing. /// REASON TEST WASN'T ORIGINALLY PRESENT: Missed test. /// /// This test ensures that two items with duplicate attributes end up in exactly one batching /// bucket. /// </summary> [Fact] public void Regress_Mutation_DuplicateBatchingBucketsAreFoldedTogether() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); List<string> parameters = new List<string>(); parameters.Add("%(File.Culture)"); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); List<ProjectItemInstance> items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "File", "a.foo", project.FullPath)); items.Add(new ProjectItemInstance(project, "File", "b.foo", project.FullPath)); // Need at least two items for this test case to ensure multiple buckets might be possible itemsByType.ImportItems(items); PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); List<ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), null); // If duplicate buckets have been folded correctly, then there will be exactly one bucket here // containing both a.foo and b.foo. Assert.Single(buckets); } [Fact] public void Simple() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <AToB Include=""a;b""/> </ItemGroup> <Target Name=""Build""> <CreateItem Include=""%(AToB.Identity)""> <Output ItemName=""AToBBatched"" TaskParameter=""Include""/> </CreateItem> <Message Text=""[AToBBatched: @(AToBBatched)]""/> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[AToBBatched: a;b]"); } /// <summary> /// When removing an item in a target which is batched and called by call target there was an exception thrown /// due to us adding the same item instance to the remove item lists when merging the lookups between the two batches. /// The fix was to not add the item to the remove list if it already exists. /// </summary> [Fact] public void Regress72803() { string content = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" DefaultTargets=""ReleaseBuild""> <ItemGroup> <Environments Include=""dev"" /> <Environments Include=""prod"" /> <ItemsToZip Include=""1"" /> </ItemGroup> <Target Name=""ReleaseBuild""> <CallTarget Targets=""MakeAppPackage;MakeDbPackage""/> </Target> <Target Name=""MakeAppPackage"" Outputs=""%(Environments.Identity)""> <ItemGroup> <ItemsToZip Include=""%(Environments.Identity).msi"" /> </ItemGroup> </Target> <Target Name=""MakeDbPackage"" Outputs=""%(Environments.Identity)""> <Message Text=""Item Before:%(Environments.Identity) @(ItemsToZip)"" /> <ItemGroup> <ItemsToZip Remove=""@(ItemsToZip)"" /> </ItemGroup> <Message Text=""Item After:%(Environments.Identity) @(ItemsToZip)"" Condition=""'@(ItemsToZip)' != ''"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("Item Before:dev 1"); log.AssertLogContains("Item Before:prod 1"); log.AssertLogDoesntContain("Item After:dev 1"); log.AssertLogDoesntContain("Item After:prod 1"); } /// <summary> /// Regress a bug where batching over an item list seemed to have /// items for that list even in buckets where there should be none, because /// it was batching over metadata that only other list/s had. /// </summary> [Fact] public void BucketsWithEmptyListForBatchedItemList() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <i Include=""b""/> <j Include=""a""> <k>x</k> </j> </ItemGroup> <Target Name=""t""> <ItemGroup> <Obj Condition=""'%(j.k)'==''"" Include=""@(j->'%(Filename).obj');%(i.foo)""/> </ItemGroup> <Message Text=""@(Obj)"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogDoesntContain("a.obj"); } /// <summary> /// Bug for Targets instead of Tasks. /// </summary> [Fact] public void BucketsWithEmptyListForTargetBatchedItemList() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <a Include=""a1""/> <b Include=""b1""/> </ItemGroup> <Target Name=""t"" Outputs=""%(a.Identity)%(b.identity)""> <Message Text=""[a=@(a) b=@(b)]"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[a=a1 b=]"); log.AssertLogContains("[a= b=b1]"); } /// <summary> /// A batching target that has no outputs should still run. /// This is how we shipped before, although Jay pointed out it's odd. /// </summary> [Fact] public void BatchOnEmptyOutput() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <File Include=""$(foo)"" /> </ItemGroup> <!-- Should not run as the single batch has no outputs --> <Target Name=""b"" Outputs=""%(File.Identity)""><Message Text=""[@(File)]"" /></Target> <Target Name=""a"" DependsOnTargets=""b""> <Message Text=""[a]"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[]"); } /// <summary> /// Every batch should get its own new task object. /// We verify this by using the Warning class. If the same object is being reused, /// the second warning would have the code from the first use of the task. /// </summary> [Fact] public void EachBatchGetsASeparateTaskObject() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <i Include=""i1""> <Code>high</Code> </i> <i Include=""i2""/> </ItemGroup> <Target Name=""t""> <Warning Text=""@(i)"" Code=""%(i.Code)""/> </Target> </Project>"; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); Assert.Equal("high", log.Warnings[0].Code); Assert.Null(log.Warnings[1].Code); } /// <summary> /// It is important that the batching engine invokes the different batches in the same /// order as the items are declared in the project, especially when batching is simply /// being used as a "for loop". /// </summary> [Fact] public void BatcherPreservesItemOrderWithinASingleItemList() { string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <AToZ Include=""a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z""/> <ZToA Include=""z;y;x;w;v;u;t;s;r;q;p;o;n;m;l;k;j;i;h;g;f;e;d;c;b;a""/> </ItemGroup> <Target Name=""Build""> <CreateItem Include=""%(AToZ.Identity)""> <Output ItemName=""AToZBatched"" TaskParameter=""Include""/> </CreateItem> <CreateItem Include=""%(ZToA.Identity)""> <Output ItemName=""ZToABatched"" TaskParameter=""Include""/> </CreateItem> <Message Text=""AToZBatched: @(AToZBatched)""/> <Message Text=""ZToABatched: @(ZToABatched)""/> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("AToZBatched: a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z"); log.AssertLogContains("ZToABatched: z;y;x;w;v;u;t;s;r;q;p;o;n;m;l;k;j;i;h;g;f;e;d;c;b;a"); } /// <summary> /// Undefined and empty metadata values should not be distinguished when bucketing. /// This is the same as previously shipped. /// </summary> [Fact] public void UndefinedAndEmptyMetadataValues() { string content = @" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <i Include='i1'/> <i Include='i2'> <m></m> </i> <i Include='i3'> <m>m1</m> </i> </ItemGroup> <Target Name='Build'> <Message Text='[@(i) %(i.m)]'/> </Target> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(content)))); MockLogger logger = new MockLogger(); project.Build(logger); logger.AssertLogContains("[i1;i2 ]", "[i3 m1]"); } private static Lookup CreateLookup(ItemDictionary<ProjectItemInstance> itemsByType, PropertyDictionary<ProjectPropertyInstance> properties) { return new Lookup(itemsByType, properties); } } }
//------------------------------------------------------------------------------ // <copyright file="NetworkCredential.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.Win32; /// <devdoc> /// <para>Provides credentials for password-based /// authentication schemes such as basic, digest, NTLM and Kerberos.</para> /// </devdoc> public class NetworkCredential : ICredentials,ICredentialsByHost { private static volatile EnvironmentPermission m_environmentUserNamePermission; private static volatile EnvironmentPermission m_environmentDomainNamePermission; private static readonly object lockingObject = new object(); private string m_domain; private string m_userName; #if !FEATURE_PAL private SecureString m_password; #else //FEATURE_PAL private string m_password; #endif //FEATURE_PAL public NetworkCredential() : this(string.Empty, string.Empty, string.Empty) { } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.NetworkCredential'/> /// class with name and password set as specified. /// </para> /// </devdoc> public NetworkCredential(string userName, string password) : this(userName, password, string.Empty) { } #if !FEATURE_PAL /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.NetworkCredential'/> /// class with name and password set as specified. /// </para> /// </devdoc> public NetworkCredential(string userName, SecureString password) : this(userName, password, string.Empty) { } #endif //!FEATURE_PAL /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.NetworkCredential'/> /// class with name and password set as specified. /// </para> /// </devdoc> public NetworkCredential(string userName, string password, string domain) { UserName = userName; Password = password; Domain = domain; } #if !FEATURE_PAL /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.NetworkCredential'/> /// class with name and password set as specified. /// </para> /// </devdoc> public NetworkCredential(string userName, SecureString password, string domain) { UserName = userName; SecurePassword = password; Domain = domain; } #endif //!FEATURE_PAL void InitializePart1() { if (m_environmentUserNamePermission == null) { lock(lockingObject) { if (m_environmentUserNamePermission == null) { m_environmentDomainNamePermission = new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERDOMAIN"); m_environmentUserNamePermission = new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"); } } } } /// <devdoc> /// <para> /// The user name associated with this credential. /// </para> /// </devdoc> public string UserName { get { InitializePart1(); m_environmentUserNamePermission.Demand(); return InternalGetUserName(); } set { if (value == null) m_userName = String.Empty; else m_userName = value; // GlobalLog.Print("NetworkCredential::set_UserName: m_userName: \"" + m_userName + "\"" ); } } /// <devdoc> /// <para> /// The password for the user name. /// </para> /// </devdoc> public string Password { get { ExceptionHelper.UnmanagedPermission.Demand(); return InternalGetPassword(); } set { #if FEATURE_PAL if (value == null) m_password = String.Empty; else m_password = value; // GlobalLog.Print("NetworkCredential::set_Password: m_password: \"" + m_password + "\"" ); #else //!FEATURE_PAL m_password = UnsafeNclNativeMethods.SecureStringHelper.CreateSecureString(value); // GlobalLog.Print("NetworkCredential::set_Password: value = " + value); // GlobalLog.Print("NetworkCredential::set_Password: m_password:"); // GlobalLog.Dump(m_password); #endif //!FEATURE_PAL } } #if !FEATURE_PAL /// <devdoc> /// <para> /// The password for the user name. /// </para> /// </devdoc> public SecureString SecurePassword { get { ExceptionHelper.UnmanagedPermission.Demand(); return InternalGetSecurePassword().Copy(); } set { if (value == null) m_password = new SecureString(); // makes 0 length string else m_password = value.Copy(); } } #endif //!FEATURE_PAL /// <devdoc> /// <para> /// The machine name that verifies /// the credentials. Usually this is the host machine. /// </para> /// </devdoc> public string Domain { get { InitializePart1(); m_environmentDomainNamePermission.Demand(); return InternalGetDomain(); } set { if (value == null) m_domain = String.Empty; else m_domain = value; // GlobalLog.Print("NetworkCredential::set_Domain: m_domain: \"" + m_domain + "\"" ); } } internal string InternalGetUserName() { // GlobalLog.Print("NetworkCredential::get_UserName: returning \"" + m_userName + "\""); return m_userName; } internal string InternalGetPassword() { #if FEATURE_PAL // GlobalLog.Print("NetworkCredential::get_Password: returning \"" + m_password + "\""); return m_password; #else //!FEATURE_PAL string decryptedString = UnsafeNclNativeMethods.SecureStringHelper.CreateString(m_password); // GlobalLog.Print("NetworkCredential::get_Password: returning \"" + decryptedString + "\""); return decryptedString; #endif //!FEATURE_PAL } #if !FEATURE_PAL internal SecureString InternalGetSecurePassword() { return m_password; } #endif //!FEATURE_PAL internal string InternalGetDomain() { // GlobalLog.Print("NetworkCredential::get_Domain: returning \"" + m_domain + "\""); return m_domain; } internal string InternalGetDomainUserName() { string domainUserName = InternalGetDomain(); if (domainUserName.Length != 0) domainUserName += "\\"; domainUserName += InternalGetUserName(); return domainUserName; } /// <devdoc> /// <para> /// Returns an instance of the NetworkCredential class for a Uri and /// authentication type. /// </para> /// </devdoc> public NetworkCredential GetCredential(Uri uri, String authType) { return this; } public NetworkCredential GetCredential(string host, int port, String authenticationType) { return this; } #if DEBUG // this method is only called as part of an assert internal bool IsEqualTo(object compObject) { if ((object)compObject == null) return false; if ((object)this == (object)compObject) return true; NetworkCredential compCred = compObject as NetworkCredential; if ((object)compCred == null) return false; #if FEATURE_PAL return(InternalGetUserName() == compCred.InternalGetUserName() && InternalGetPassword() == compCred.InternalGetPassword() && InternalGetDomain() == compCred.InternalGetDomain()); #else //!FEATURE_PAL return (InternalGetUserName() == compCred.InternalGetUserName() && InternalGetDomain() == compCred.InternalGetDomain() && UnsafeNclNativeMethods.SecureStringHelper.AreEqualValues(InternalGetSecurePassword(), compCred.InternalGetSecurePassword())); #endif //!FEATURE_PAL } #endif //DEBUG } // class NetworkCredential } // namespace System.Net
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp.Swizzle { /// <summary> /// Temporary vector of type T with 2 components, used for implementing swizzling for gvec2. /// </summary> [Serializable] [DataContract(Namespace = "swizzle")] [StructLayout(LayoutKind.Sequential)] public struct swizzle_gvec2<T> { #region Fields /// <summary> /// x-component /// </summary> [DataMember] internal readonly T x; /// <summary> /// y-component /// </summary> [DataMember] internal readonly T y; #endregion #region Constructors /// <summary> /// Constructor for swizzle_gvec2. /// </summary> internal swizzle_gvec2(T x, T y) { this.x = x; this.y = y; } #endregion #region Properties /// <summary> /// Returns gvec2.xx swizzling. /// </summary> public gvec2<T> xx => new gvec2<T>(x, x); /// <summary> /// Returns gvec2.rr swizzling (equivalent to gvec2.xx). /// </summary> public gvec2<T> rr => new gvec2<T>(x, x); /// <summary> /// Returns gvec2.xxx swizzling. /// </summary> public gvec3<T> xxx => new gvec3<T>(x, x, x); /// <summary> /// Returns gvec2.rrr swizzling (equivalent to gvec2.xxx). /// </summary> public gvec3<T> rrr => new gvec3<T>(x, x, x); /// <summary> /// Returns gvec2.xxxx swizzling. /// </summary> public gvec4<T> xxxx => new gvec4<T>(x, x, x, x); /// <summary> /// Returns gvec2.rrrr swizzling (equivalent to gvec2.xxxx). /// </summary> public gvec4<T> rrrr => new gvec4<T>(x, x, x, x); /// <summary> /// Returns gvec2.xxxy swizzling. /// </summary> public gvec4<T> xxxy => new gvec4<T>(x, x, x, y); /// <summary> /// Returns gvec2.rrrg swizzling (equivalent to gvec2.xxxy). /// </summary> public gvec4<T> rrrg => new gvec4<T>(x, x, x, y); /// <summary> /// Returns gvec2.xxy swizzling. /// </summary> public gvec3<T> xxy => new gvec3<T>(x, x, y); /// <summary> /// Returns gvec2.rrg swizzling (equivalent to gvec2.xxy). /// </summary> public gvec3<T> rrg => new gvec3<T>(x, x, y); /// <summary> /// Returns gvec2.xxyx swizzling. /// </summary> public gvec4<T> xxyx => new gvec4<T>(x, x, y, x); /// <summary> /// Returns gvec2.rrgr swizzling (equivalent to gvec2.xxyx). /// </summary> public gvec4<T> rrgr => new gvec4<T>(x, x, y, x); /// <summary> /// Returns gvec2.xxyy swizzling. /// </summary> public gvec4<T> xxyy => new gvec4<T>(x, x, y, y); /// <summary> /// Returns gvec2.rrgg swizzling (equivalent to gvec2.xxyy). /// </summary> public gvec4<T> rrgg => new gvec4<T>(x, x, y, y); /// <summary> /// Returns gvec2.xy swizzling. /// </summary> public gvec2<T> xy => new gvec2<T>(x, y); /// <summary> /// Returns gvec2.rg swizzling (equivalent to gvec2.xy). /// </summary> public gvec2<T> rg => new gvec2<T>(x, y); /// <summary> /// Returns gvec2.xyx swizzling. /// </summary> public gvec3<T> xyx => new gvec3<T>(x, y, x); /// <summary> /// Returns gvec2.rgr swizzling (equivalent to gvec2.xyx). /// </summary> public gvec3<T> rgr => new gvec3<T>(x, y, x); /// <summary> /// Returns gvec2.xyxx swizzling. /// </summary> public gvec4<T> xyxx => new gvec4<T>(x, y, x, x); /// <summary> /// Returns gvec2.rgrr swizzling (equivalent to gvec2.xyxx). /// </summary> public gvec4<T> rgrr => new gvec4<T>(x, y, x, x); /// <summary> /// Returns gvec2.xyxy swizzling. /// </summary> public gvec4<T> xyxy => new gvec4<T>(x, y, x, y); /// <summary> /// Returns gvec2.rgrg swizzling (equivalent to gvec2.xyxy). /// </summary> public gvec4<T> rgrg => new gvec4<T>(x, y, x, y); /// <summary> /// Returns gvec2.xyy swizzling. /// </summary> public gvec3<T> xyy => new gvec3<T>(x, y, y); /// <summary> /// Returns gvec2.rgg swizzling (equivalent to gvec2.xyy). /// </summary> public gvec3<T> rgg => new gvec3<T>(x, y, y); /// <summary> /// Returns gvec2.xyyx swizzling. /// </summary> public gvec4<T> xyyx => new gvec4<T>(x, y, y, x); /// <summary> /// Returns gvec2.rggr swizzling (equivalent to gvec2.xyyx). /// </summary> public gvec4<T> rggr => new gvec4<T>(x, y, y, x); /// <summary> /// Returns gvec2.xyyy swizzling. /// </summary> public gvec4<T> xyyy => new gvec4<T>(x, y, y, y); /// <summary> /// Returns gvec2.rggg swizzling (equivalent to gvec2.xyyy). /// </summary> public gvec4<T> rggg => new gvec4<T>(x, y, y, y); /// <summary> /// Returns gvec2.yx swizzling. /// </summary> public gvec2<T> yx => new gvec2<T>(y, x); /// <summary> /// Returns gvec2.gr swizzling (equivalent to gvec2.yx). /// </summary> public gvec2<T> gr => new gvec2<T>(y, x); /// <summary> /// Returns gvec2.yxx swizzling. /// </summary> public gvec3<T> yxx => new gvec3<T>(y, x, x); /// <summary> /// Returns gvec2.grr swizzling (equivalent to gvec2.yxx). /// </summary> public gvec3<T> grr => new gvec3<T>(y, x, x); /// <summary> /// Returns gvec2.yxxx swizzling. /// </summary> public gvec4<T> yxxx => new gvec4<T>(y, x, x, x); /// <summary> /// Returns gvec2.grrr swizzling (equivalent to gvec2.yxxx). /// </summary> public gvec4<T> grrr => new gvec4<T>(y, x, x, x); /// <summary> /// Returns gvec2.yxxy swizzling. /// </summary> public gvec4<T> yxxy => new gvec4<T>(y, x, x, y); /// <summary> /// Returns gvec2.grrg swizzling (equivalent to gvec2.yxxy). /// </summary> public gvec4<T> grrg => new gvec4<T>(y, x, x, y); /// <summary> /// Returns gvec2.yxy swizzling. /// </summary> public gvec3<T> yxy => new gvec3<T>(y, x, y); /// <summary> /// Returns gvec2.grg swizzling (equivalent to gvec2.yxy). /// </summary> public gvec3<T> grg => new gvec3<T>(y, x, y); /// <summary> /// Returns gvec2.yxyx swizzling. /// </summary> public gvec4<T> yxyx => new gvec4<T>(y, x, y, x); /// <summary> /// Returns gvec2.grgr swizzling (equivalent to gvec2.yxyx). /// </summary> public gvec4<T> grgr => new gvec4<T>(y, x, y, x); /// <summary> /// Returns gvec2.yxyy swizzling. /// </summary> public gvec4<T> yxyy => new gvec4<T>(y, x, y, y); /// <summary> /// Returns gvec2.grgg swizzling (equivalent to gvec2.yxyy). /// </summary> public gvec4<T> grgg => new gvec4<T>(y, x, y, y); /// <summary> /// Returns gvec2.yy swizzling. /// </summary> public gvec2<T> yy => new gvec2<T>(y, y); /// <summary> /// Returns gvec2.gg swizzling (equivalent to gvec2.yy). /// </summary> public gvec2<T> gg => new gvec2<T>(y, y); /// <summary> /// Returns gvec2.yyx swizzling. /// </summary> public gvec3<T> yyx => new gvec3<T>(y, y, x); /// <summary> /// Returns gvec2.ggr swizzling (equivalent to gvec2.yyx). /// </summary> public gvec3<T> ggr => new gvec3<T>(y, y, x); /// <summary> /// Returns gvec2.yyxx swizzling. /// </summary> public gvec4<T> yyxx => new gvec4<T>(y, y, x, x); /// <summary> /// Returns gvec2.ggrr swizzling (equivalent to gvec2.yyxx). /// </summary> public gvec4<T> ggrr => new gvec4<T>(y, y, x, x); /// <summary> /// Returns gvec2.yyxy swizzling. /// </summary> public gvec4<T> yyxy => new gvec4<T>(y, y, x, y); /// <summary> /// Returns gvec2.ggrg swizzling (equivalent to gvec2.yyxy). /// </summary> public gvec4<T> ggrg => new gvec4<T>(y, y, x, y); /// <summary> /// Returns gvec2.yyy swizzling. /// </summary> public gvec3<T> yyy => new gvec3<T>(y, y, y); /// <summary> /// Returns gvec2.ggg swizzling (equivalent to gvec2.yyy). /// </summary> public gvec3<T> ggg => new gvec3<T>(y, y, y); /// <summary> /// Returns gvec2.yyyx swizzling. /// </summary> public gvec4<T> yyyx => new gvec4<T>(y, y, y, x); /// <summary> /// Returns gvec2.gggr swizzling (equivalent to gvec2.yyyx). /// </summary> public gvec4<T> gggr => new gvec4<T>(y, y, y, x); /// <summary> /// Returns gvec2.yyyy swizzling. /// </summary> public gvec4<T> yyyy => new gvec4<T>(y, y, y, y); /// <summary> /// Returns gvec2.gggg swizzling (equivalent to gvec2.yyyy). /// </summary> public gvec4<T> gggg => new gvec4<T>(y, y, y, y); #endregion } }
using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Android.Content; using System.Timers; using System.Linq.Expressions; using Android.Util; using Android.Animation; using Android.Graphics; namespace XamarinStore { class ProductDetailsFragment : Fragment, ViewTreeObserver.IOnGlobalLayoutListener { ImageView productImage; int currentIndex = 0; Product currentProduct; bool shouldAnimatePop; BadgeDrawable basketBadge; public Action<Product> AddToBasket = delegate {}; string[] images = new string[0]; bool cached; int slidingDelta; Spinner sizeSpinner; Spinner colorSpinner; KenBurnsDrawable productDrawable; ValueAnimator kenBurnsMovement; ValueAnimator kenBurnsAlpha; public ProductDetailsFragment () { } public ProductDetailsFragment (Product product,int slidingDelta ) { if (product == null) throw new ArgumentNullException("product"); this.slidingDelta = slidingDelta; currentProduct = product; images = product.ImageUrls.ToArray().Shuffle() ?? new string[0]; } public override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); RetainInstance = true; SetHasOptionsMenu (true); } public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.Inflate (Resource.Layout.ProductDetail, null, true); } public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); productImage = View.FindViewById<ImageView> (Resource.Id.productImage); sizeSpinner = View.FindViewById<Spinner> (Resource.Id.productSize); colorSpinner = View.FindViewById<Spinner> (Resource.Id.productColor); var addToBasket = View.FindViewById<Button> (Resource.Id.addToBasket); addToBasket.Click += delegate { currentProduct.Size = currentProduct.Sizes [sizeSpinner.SelectedItemPosition]; currentProduct.Color = currentProduct.Colors [colorSpinner.SelectedItemPosition]; shouldAnimatePop = true; Activity.FragmentManager.PopBackStack(); AddToBasket (currentProduct); }; View.FindViewById<TextView> (Resource.Id.productTitle).Text = currentProduct.Name ?? string.Empty; View.FindViewById<TextView> (Resource.Id.productPrice).Text = currentProduct.PriceDescription ?? string.Empty; View.FindViewById<TextView> (Resource.Id.productDescription).Text = currentProduct.Description ?? string.Empty; ((SlidingLayout)View).InitialMainViewDelta = slidingDelta; LoadOptions (); } void LoadOptions() { var sizeAdapter = new ArrayAdapter<ProductSize> (Activity, Android.Resource.Layout.SimpleSpinnerDropDownItem, currentProduct.Sizes); sizeAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); sizeSpinner.Adapter = sizeAdapter; sizeSpinner.SetSelection (currentProduct.Sizes.IndexOf (currentProduct.Size)); var colorAdapter = new ArrayAdapter<ProductColor> (Activity, Android.Resource.Layout.SimpleSpinnerDropDownItem, currentProduct.Colors); colorAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); colorSpinner.Adapter = colorAdapter; } public override void OnStart () { base.OnStart (); AnimateImages (); } public override void OnStop () { base.OnStop (); if (kenBurnsAlpha != null) kenBurnsAlpha.Cancel (); if (kenBurnsMovement != null) kenBurnsMovement.Cancel (); } public override void OnCreateOptionsMenu (IMenu menu, MenuInflater inflater) { inflater.Inflate (Resource.Menu.menu, menu); var cartItem = menu.FindItem (Resource.Id.cart_menu_item); cartItem.SetIcon ((basketBadge = new BadgeDrawable (cartItem.Icon))); var order = WebService.Shared.CurrentOrder; basketBadge.Count = order.Products.Count; order.ProductsChanged += (sender, e) => { basketBadge.SetCountAnimated (order.Products.Count); }; base.OnCreateOptionsMenu (menu, inflater); } public override Android.Animation.Animator OnCreateAnimator (FragmentTransit transit, bool enter, int nextAnim) { if (!enter && shouldAnimatePop) return AnimatorInflater.LoadAnimator (View.Context, Resource.Animation.add_to_basket_in); return base.OnCreateAnimator (transit, enter, nextAnim); } void AnimateImages () { if (images.Length < 1) return; if (images.Length == 1) { //No need to await the change #pragma warning disable 4014 Images.SetImageFromUrlAsync (productImage, Product.ImageForSize (images [0], Images.ScreenWidth)); #pragma warning restore 4014 return; } productImage.ViewTreeObserver.AddOnGlobalLayoutListener (this); } public async void OnGlobalLayout () { productImage.ViewTreeObserver.RemoveGlobalOnLayoutListener (this); const int DeltaX = 100; var img1 = Images.FromUrl (Product.ImageForSize (images [0], Images.ScreenWidth)); var img2 = Images.FromUrl (Product.ImageForSize (images [1], Images.ScreenWidth)); productDrawable = new KenBurnsDrawable (Color.DarkBlue); productDrawable.FirstBitmap = await img1; productDrawable.SecondBitmap = await img2; productImage.SetImageDrawable (productDrawable); currentIndex++; var evaluator = new MatrixEvaluator (); var finalMatrix = new Matrix (); finalMatrix.SetTranslate (-DeltaX, -(float)productDrawable.FirstBitmap.Height / 1.3f + (float)productImage.Height); finalMatrix.PostScale (1.27f, 1.27f); kenBurnsMovement = ValueAnimator.OfObject (evaluator, new Matrix (), finalMatrix); kenBurnsMovement.Update += (sender, e) => productDrawable.SetMatrix ((Matrix)e.Animation.AnimatedValue); kenBurnsMovement.SetDuration (14000); kenBurnsMovement.RepeatMode = ValueAnimatorRepeatMode.Reverse; kenBurnsMovement.RepeatCount = ValueAnimator.Infinite; kenBurnsMovement.Start (); kenBurnsAlpha = ObjectAnimator.OfInt (productDrawable, "alpha", 0, 0, 0, 255, 255, 255); kenBurnsAlpha.SetDuration (kenBurnsMovement.Duration); kenBurnsAlpha.RepeatMode = ValueAnimatorRepeatMode.Reverse; kenBurnsAlpha.RepeatCount = ValueAnimator.Infinite; kenBurnsAlpha.AnimationRepeat += (sender, e) => NextImage (); kenBurnsAlpha.Start (); } async void NextImage () { currentIndex = (currentIndex + 1) % images.Length; var image = images [currentIndex]; await Images.SetImageFromUrlAsync (productDrawable, Product.ImageForSize (image, Images.ScreenWidth)); PrecacheNextImage (); } void PrecacheNextImage() { if (currentIndex + 1 >= images.Length) cached = true; if (cached) return; var next = currentIndex + 1; var image = images [next]; //No need to await the precache to finish #pragma warning disable 4014 FileCache.Download (Product.ImageForSize (image, Images.ScreenWidth)); #pragma warning restore 4014 } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.IO; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using RVA = System.UInt32; namespace Mono.Cecil.PE { sealed class ImageWriter : BinaryStreamWriter { readonly ModuleDefinition module; readonly MetadataBuilder metadata; readonly TextMap text_map; readonly internal Disposable<Stream> stream; readonly string runtime_version; ImageDebugHeader debug_header; ByteBuffer win32_resources; const uint pe_header_size = 0x98u; const uint section_header_size = 0x28u; const uint file_alignment = 0x200; const uint section_alignment = 0x2000; const ulong image_base = 0x00400000; internal const RVA text_rva = 0x2000; readonly bool pe64; readonly bool has_reloc; internal Section text; internal Section rsrc; internal Section reloc; ushort sections; ImageWriter (ModuleDefinition module, string runtime_version, MetadataBuilder metadata, Disposable<Stream> stream, bool metadataOnly = false) : base (stream.value) { this.module = module; this.runtime_version = runtime_version; this.text_map = metadata.text_map; this.stream = stream; this.metadata = metadata; if (metadataOnly) return; this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64 || module.Architecture == TargetArchitecture.ARM64; this.has_reloc = module.Architecture == TargetArchitecture.I386; this.GetDebugHeader (); this.GetWin32Resources (); this.BuildTextMap (); this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc? } void GetDebugHeader () { var symbol_writer = metadata.symbol_writer; if (symbol_writer != null) debug_header = symbol_writer.GetDebugHeader (); if (module.HasDebugHeader) { var header = module.GetDebugHeader (); var deterministic = header.GetDeterministicEntry (); if (deterministic == null) return; debug_header = debug_header.AddDeterministicEntry (); } } void GetWin32Resources () { if (!module.HasImage) return; DataDirectory win32_resources_directory = module.Image.Win32Resources; var size = win32_resources_directory.Size; if (size > 0) { win32_resources = module.Image.GetReaderAt (win32_resources_directory.VirtualAddress, size, (s, reader) => new ByteBuffer (reader.ReadBytes ((int) s))); } } public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream) { var writer = new ImageWriter (module, module.runtime_version, metadata, stream); writer.BuildSections (); return writer; } public static ImageWriter CreateDebugWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream) { var writer = new ImageWriter (module, "PDB v1.0", metadata, stream, metadataOnly: true); var length = metadata.text_map.GetLength (); writer.text = new Section { SizeOfRawData = length, VirtualSize = length }; return writer; } void BuildSections () { var has_win32_resources = win32_resources != null; if (has_win32_resources) sections++; text = CreateSection (".text", text_map.GetLength (), null); var previous = text; if (has_win32_resources) { rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous); PatchWin32Resources (win32_resources); previous = rsrc; } if (has_reloc) reloc = CreateSection (".reloc", 12u, previous); } Section CreateSection (string name, uint size, Section previous) { return new Section { Name = name, VirtualAddress = previous != null ? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment) : text_rva, VirtualSize = size, PointerToRawData = previous != null ? previous.PointerToRawData + previous.SizeOfRawData : Align (GetHeaderSize (), file_alignment), SizeOfRawData = Align (size, file_alignment) }; } static uint Align (uint value, uint align) { align--; return (value + align) & ~align; } void WriteDOSHeader () { Write (new byte [] { // dos header start 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // lfanew 0x80, 0x00, 0x00, 0x00, // dos header end 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); } ushort SizeOfOptionalHeader () { return (ushort) (!pe64 ? 0xe0 : 0xf0); } void WritePEFileHeader () { WriteUInt32 (0x00004550); // Magic WriteUInt16 ((ushort) module.Architecture); // Machine WriteUInt16 (sections); // NumberOfSections WriteUInt32 (metadata.timestamp); WriteUInt32 (0); // PointerToSymbolTable WriteUInt32 (0); // NumberOfSymbols WriteUInt16 (SizeOfOptionalHeader ()); // SizeOfOptionalHeader const ushort LargeAddressAware = 0x0020; // ExecutableImage | (!pe64 ? 32BitsMachine : LargeAddressAware) var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : LargeAddressAware)); if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule) characteristics |= 0x2000; if (module.Image != null && (module.Image.Characteristics & LargeAddressAware) != 0) characteristics |= LargeAddressAware; WriteUInt16 (characteristics); // Characteristics } Section LastSection () { if (reloc != null) return reloc; if (rsrc != null) return rsrc; return text; } void WriteOptionalHeaders () { WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic WriteUInt16 (module.linker_version); WriteUInt32 (text.SizeOfRawData); // CodeSize WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0) + (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize WriteUInt32 (0); // UninitializedDataSize var startub_stub = text_map.GetRange (TextSegment.StartupStub); WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA WriteUInt32 (text_rva); // BaseOfCode if (!pe64) { WriteUInt32 (0); // BaseOfData WriteUInt32 ((uint) image_base); // ImageBase } else { WriteUInt64 (image_base); // ImageBase } WriteUInt32 (section_alignment); // SectionAlignment WriteUInt32 (file_alignment); // FileAlignment WriteUInt16 (4); // OSMajor WriteUInt16 (0); // OSMinor WriteUInt16 (0); // UserMajor WriteUInt16 (0); // UserMinor WriteUInt16 (module.subsystem_major); // SubSysMajor WriteUInt16 (module.subsystem_minor); // SubSysMinor WriteUInt32 (0); // Reserved var last_section = LastSection(); WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize WriteUInt32 (text.PointerToRawData); // HeaderSize WriteUInt32 (0); // Checksum WriteUInt16 (GetSubSystem ()); // SubSystem WriteUInt16 ((ushort) module.Characteristics); // DLLFlags if (!pe64) { const uint stack_reserve = 0x100000; const uint stack_commit = 0x1000; const uint heap_reserve = 0x100000; const uint heap_commit = 0x1000; WriteUInt32 (stack_reserve); WriteUInt32 (stack_commit); WriteUInt32 (heap_reserve); WriteUInt32 (heap_commit); } else { const ulong stack_reserve = 0x400000; const ulong stack_commit = 0x4000; const ulong heap_reserve = 0x100000; const ulong heap_commit = 0x2000; WriteUInt64 (stack_reserve); WriteUInt64 (stack_commit); WriteUInt64 (heap_reserve); WriteUInt64 (heap_commit); } WriteUInt32 (0); // LoaderFlags WriteUInt32 (16); // NumberOfDataDir WriteZeroDataDirectory (); // ExportTable WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable if (rsrc != null) { // ResourceTable WriteUInt32 (rsrc.VirtualAddress); WriteUInt32 (rsrc.VirtualSize); } else WriteZeroDataDirectory (); WriteZeroDataDirectory (); // ExceptionTable WriteZeroDataDirectory (); // CertificateTable WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable WriteUInt32 (reloc != null ? reloc.VirtualSize : 0); if (text_map.GetLength (TextSegment.DebugDirectory) > 0) { WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory)); WriteUInt32 ((uint) (debug_header.Entries.Length * ImageDebugDirectory.Size)); } else WriteZeroDataDirectory (); WriteZeroDataDirectory (); // Copyright WriteZeroDataDirectory (); // GlobalPtr WriteZeroDataDirectory (); // TLSTable WriteZeroDataDirectory (); // LoadConfigTable WriteZeroDataDirectory (); // BoundImport WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT WriteZeroDataDirectory (); // DelayImportDesc WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader WriteZeroDataDirectory (); // Reserved } void WriteZeroDataDirectory () { WriteUInt32 (0); WriteUInt32 (0); } ushort GetSubSystem () { switch (module.Kind) { case ModuleKind.Console: case ModuleKind.Dll: case ModuleKind.NetModule: return 0x3; case ModuleKind.Windows: return 0x2; default: throw new ArgumentOutOfRangeException (); } } void WriteSectionHeaders () { WriteSection (text, 0x60000020); if (rsrc != null) WriteSection (rsrc, 0x40000040); if (reloc != null) WriteSection (reloc, 0x42000040); } void WriteSection (Section section, uint characteristics) { var name = new byte [8]; var sect_name = section.Name; for (int i = 0; i < sect_name.Length; i++) name [i] = (byte) sect_name [i]; WriteBytes (name); WriteUInt32 (section.VirtualSize); WriteUInt32 (section.VirtualAddress); WriteUInt32 (section.SizeOfRawData); WriteUInt32 (section.PointerToRawData); WriteUInt32 (0); // PointerToRelocations WriteUInt32 (0); // PointerToLineNumbers WriteUInt16 (0); // NumberOfRelocations WriteUInt16 (0); // NumberOfLineNumbers WriteUInt32 (characteristics); } uint GetRVAFileOffset (Section section, RVA rva) { return section.PointerToRawData + rva - section.VirtualAddress; } void MoveTo (uint pointer) { BaseStream.Seek (pointer, SeekOrigin.Begin); } void MoveToRVA (Section section, RVA rva) { BaseStream.Seek (GetRVAFileOffset (section, rva), SeekOrigin.Begin); } void MoveToRVA (TextSegment segment) { MoveToRVA (text, text_map.GetRVA (segment)); } void WriteRVA (RVA rva) { if (!pe64) WriteUInt32 (rva); else WriteUInt64 (rva); } void PrepareSection (Section section) { MoveTo (section.PointerToRawData); const int buffer_size = 4096; if (section.SizeOfRawData <= buffer_size) { Write (new byte [section.SizeOfRawData]); MoveTo (section.PointerToRawData); return; } var written = 0; var buffer = new byte [buffer_size]; while (written != section.SizeOfRawData) { var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size); Write (buffer, 0, write_size); written += write_size; } MoveTo (section.PointerToRawData); } void WriteText () { PrepareSection (text); // ImportAddressTable if (has_reloc) { WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable)); WriteRVA (0); } // CLIHeader WriteUInt32 (0x48); WriteUInt16 (2); WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5)); WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader)); WriteUInt32 (GetMetadataLength ()); WriteUInt32 ((uint) module.Attributes); WriteUInt32 (metadata.entry_point.ToUInt32 ()); WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources)); WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature)); WriteZeroDataDirectory (); // CodeManagerTable WriteZeroDataDirectory (); // VTableFixups WriteZeroDataDirectory (); // ExportAddressTableJumps WriteZeroDataDirectory (); // ManagedNativeHeader // Code MoveToRVA (TextSegment.Code); WriteBuffer (metadata.code); // Resources MoveToRVA (TextSegment.Resources); WriteBuffer (metadata.resources); // Data if (metadata.data.length > 0) { MoveToRVA (TextSegment.Data); WriteBuffer (metadata.data); } // StrongNameSignature // stays blank // MetadataHeader MoveToRVA (TextSegment.MetadataHeader); WriteMetadataHeader (); WriteMetadata (); // DebugDirectory if (text_map.GetLength (TextSegment.DebugDirectory) > 0) { MoveToRVA (TextSegment.DebugDirectory); WriteDebugDirectory (); } if (!has_reloc) return; // ImportDirectory MoveToRVA (TextSegment.ImportDirectory); WriteImportDirectory (); // StartupStub MoveToRVA (TextSegment.StartupStub); WriteStartupStub (); } uint GetMetadataLength () { return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader); } public void WriteMetadataHeader () { WriteUInt32 (0x424a5342); // Signature WriteUInt16 (1); // MajorVersion WriteUInt16 (1); // MinorVersion WriteUInt32 (0); // Reserved var version = GetZeroTerminatedString (runtime_version); WriteUInt32 ((uint) version.Length); WriteBytes (version); WriteUInt16 (0); // Flags WriteUInt16 (GetStreamCount ()); uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader); WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~"); WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings"); WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US"); WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID"); WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob"); WriteStreamHeader (ref offset, TextSegment.PdbHeap, "#Pdb"); } ushort GetStreamCount () { return (ushort) ( 1 // #~ + 1 // #Strings + (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US + (metadata.guid_heap.IsEmpty ? 0 : 1) // GUID + (metadata.blob_heap.IsEmpty ? 0 : 1) + (metadata.pdb_heap == null ? 0 : 1)); // #Blob } void WriteStreamHeader (ref uint offset, TextSegment heap, string name) { var length = (uint) text_map.GetLength (heap); if (length == 0) return; WriteUInt32 (offset); WriteUInt32 (length); WriteBytes (GetZeroTerminatedString (name)); offset += length; } static int GetZeroTerminatedStringLength (string @string) { return (@string.Length + 1 + 3) & ~3; } static byte [] GetZeroTerminatedString (string @string) { return GetString (@string, GetZeroTerminatedStringLength (@string)); } static byte [] GetSimpleString (string @string) { return GetString (@string, @string.Length); } static byte [] GetString (string @string, int length) { var bytes = new byte [length]; for (int i = 0; i < @string.Length; i++) bytes [i] = (byte) @string [i]; return bytes; } public void WriteMetadata () { WriteHeap (TextSegment.TableHeap, metadata.table_heap); WriteHeap (TextSegment.StringHeap, metadata.string_heap); WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap); WriteHeap (TextSegment.GuidHeap, metadata.guid_heap); WriteHeap (TextSegment.BlobHeap, metadata.blob_heap); WriteHeap (TextSegment.PdbHeap, metadata.pdb_heap); } void WriteHeap (TextSegment heap, HeapBuffer buffer) { if (buffer == null || buffer.IsEmpty) return; MoveToRVA (heap); WriteBuffer (buffer); } void WriteDebugDirectory () { var data_start = (int) BaseStream.Position + (debug_header.Entries.Length * ImageDebugDirectory.Size); for (var i = 0; i < debug_header.Entries.Length; i++) { var entry = debug_header.Entries [i]; var directory = entry.Directory; WriteInt32 (directory.Characteristics); WriteInt32 (directory.TimeDateStamp); WriteInt16 (directory.MajorVersion); WriteInt16 (directory.MinorVersion); WriteInt32 ((int) directory.Type); WriteInt32 (directory.SizeOfData); WriteInt32 (directory.AddressOfRawData); WriteInt32 (data_start); data_start += entry.Data.Length; } for (var i = 0; i < debug_header.Entries.Length; i++) { var entry = debug_header.Entries [i]; WriteBytes (entry.Data); } } void WriteImportDirectory () { WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable WriteUInt32 (0); // DateTimeStamp WriteUInt32 (0); // ForwarderChain WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14); WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable)); Advance (20); // ImportLookupTable WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable)); // ImportHintNameTable MoveToRVA (TextSegment.ImportHintNameTable); WriteUInt16 (0); // Hint WriteBytes (GetRuntimeMain ()); WriteByte (0); WriteBytes (GetSimpleString ("mscoree.dll")); WriteUInt16 (0); } byte [] GetRuntimeMain () { return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule ? GetSimpleString ("_CorDllMain") : GetSimpleString ("_CorExeMain"); } void WriteStartupStub () { switch (module.Architecture) { case TargetArchitecture.I386: WriteUInt16 (0x25ff); WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable)); return; default: throw new NotSupportedException (); } } void WriteRsrc () { PrepareSection (rsrc); WriteBuffer (win32_resources); } void WriteReloc () { PrepareSection (reloc); var reloc_rva = text_map.GetRVA (TextSegment.StartupStub); reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2; var page_rva = reloc_rva & ~0xfffu; WriteUInt32 (page_rva); // PageRVA WriteUInt32 (0x000c); // Block Size switch (module.Architecture) { case TargetArchitecture.I386: WriteUInt32 (0x3000 + reloc_rva - page_rva); break; default: throw new NotSupportedException(); } } public void WriteImage () { WriteDOSHeader (); WritePEFileHeader (); WriteOptionalHeaders (); WriteSectionHeaders (); WriteText (); if (rsrc != null) WriteRsrc (); if (reloc != null) WriteReloc (); Flush (); } void BuildTextMap () { var map = text_map; map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16); map.AddMap (TextSegment.Resources, metadata.resources.length, 8); map.AddMap (TextSegment.Data, metadata.data.length, 4); if (metadata.data.length > 0) metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data)); map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4); BuildMetadataTextMap (); int debug_dir_len = 0; if (debug_header != null && debug_header.HasEntries) { var directories_len = debug_header.Entries.Length * ImageDebugDirectory.Size; var data_address = (int) map.GetNextRVA (TextSegment.BlobHeap) + directories_len; var data_len = 0; for (var i = 0; i < debug_header.Entries.Length; i++) { var entry = debug_header.Entries [i]; var directory = entry.Directory; directory.AddressOfRawData = entry.Data.Length == 0 ? 0 : data_address; entry.Directory = directory; data_len += entry.Data.Length; data_address += data_len; } debug_dir_len = directories_len + data_len; } map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4); if (!has_reloc) { var start = map.GetNextRVA (TextSegment.DebugDirectory); map.AddMap (TextSegment.ImportDirectory, new Range (start, 0)); map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0)); map.AddMap (TextSegment.StartupStub, new Range (start, 0)); return; } RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory); RVA import_hnt_rva = import_dir_rva + 48u; import_hnt_rva = (import_hnt_rva + 15u) & ~15u; uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u; RVA startup_stub_rva = import_dir_rva + import_dir_len; startup_stub_rva = module.Architecture == TargetArchitecture.IA64 ? (startup_stub_rva + 15u) & ~15u : 2 + ((startup_stub_rva + 3u) & ~3u); map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len)); map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0)); map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ())); } public void BuildMetadataTextMap () { var map = text_map; map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength (module.RuntimeVersion)); map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4); map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4); map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4); map.AddMap (TextSegment.GuidHeap, metadata.guid_heap.length, 4); map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4); map.AddMap (TextSegment.PdbHeap, metadata.pdb_heap == null ? 0 : metadata.pdb_heap.length, 4); } uint GetStartupStubLength () { switch (module.Architecture) { case TargetArchitecture.I386: return 6; default: throw new NotSupportedException (); } } int GetMetadataHeaderLength (string runtimeVersion) { return // MetadataHeader 20 + GetZeroTerminatedStringLength (runtimeVersion) // #~ header + 12 // #Strings header + 20 // #US header + (metadata.user_string_heap.IsEmpty ? 0 : 12) // #GUID header + 16 // #Blob header + (metadata.blob_heap.IsEmpty ? 0 : 16) // + (metadata.pdb_heap == null ? 0 : 16); } int GetStrongNameLength () { if (module.kind == ModuleKind.NetModule || module.Assembly == null) return 0; var public_key = module.Assembly.Name.PublicKey; if (public_key.IsNullOrEmpty ()) return 0; // in fx 2.0 the key may be from 384 to 16384 bits // so we must calculate the signature size based on // the size of the public key (minus the 32 byte header) int size = public_key.Length; if (size > 32) return size - 32; // note: size == 16 for the ECMA "key" which is replaced // by the runtime with a 1024 bits key (128 bytes) return 128; // default strongname signature size } public DataDirectory GetStrongNameSignatureDirectory () { return text_map.GetDataDirectory (TextSegment.StrongNameSignature); } public uint GetHeaderSize () { return pe_header_size + SizeOfOptionalHeader () + (sections * section_header_size); } void PatchWin32Resources (ByteBuffer resources) { PatchResourceDirectoryTable (resources); } void PatchResourceDirectoryTable (ByteBuffer resources) { resources.Advance (12); var entries = resources.ReadUInt16 () + resources.ReadUInt16 (); for (int i = 0; i < entries; i++) PatchResourceDirectoryEntry (resources); } void PatchResourceDirectoryEntry (ByteBuffer resources) { resources.Advance (4); var child = resources.ReadUInt32 (); var position = resources.position; resources.position = (int) child & 0x7fffffff; if ((child & 0x80000000) != 0) PatchResourceDirectoryTable (resources); else PatchResourceDataEntry (resources); resources.position = position; } void PatchResourceDataEntry (ByteBuffer resources) { var rva = resources.ReadUInt32 (); resources.position -= 4; resources.WriteUInt32 (rva - module.Image.Win32Resources.VirtualAddress + rsrc.VirtualAddress); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureResource { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for AutoRestResourceFlatteningTestService. /// </summary> public static partial class AutoRestResourceFlatteningTestServiceExtensions { /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> public static void PutArray(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutArrayAsync(resourceArray), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutArrayAsync(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutArrayWithHttpMessagesAsync(resourceArray, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IList<FlattenedProduct> GetArray(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetArrayAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<FlattenedProduct>> GetArrayAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetArrayWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> public static void PutDictionary(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutDictionaryAsync(resourceDictionary), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDictionaryWithHttpMessagesAsync(resourceDictionary, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, FlattenedProduct> GetDictionary(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetDictionaryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, FlattenedProduct>> GetDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDictionaryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ResourceCollection GetResourceCollection(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetResourceCollectionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceCollection> GetResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetResourceCollectionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Web; using System.Web.Hosting; using Orchard.Specs.Util; using Path = Bleroy.FluentPath.Path; namespace Orchard.Specs.Hosting { public class WebHost { private readonly Path _orchardTemp; private WebHostAgent _webHostAgent; private Path _tempSite; private Path _orchardWebPath; private Path _codeGenDir; private IEnumerable<string> _knownModules; private IEnumerable<string> _knownThemes; private IEnumerable<string> _knownBinAssemblies; public WebHost(Path orchardTemp) { _orchardTemp = orchardTemp; } public void Initialize(string templateName, string virtualDirectory, DynamicCompilationOption dynamicCompilationOption) { var stopwatch = new Stopwatch(); stopwatch.Start(); var baseDir = Path.Get(AppDomain.CurrentDomain.BaseDirectory); _tempSite = _orchardTemp.Combine(System.IO.Path.GetRandomFileName()); try { _tempSite.Delete(); } catch { } // Trying the two known relative paths to the Orchard.Web directory. // The second one is for the target "spec" in orchard.proj. _orchardWebPath = baseDir; while (!_orchardWebPath.Combine("Orchard.proj").Exists && _orchardWebPath.Parent != null) { _orchardWebPath = _orchardWebPath.Parent; } _orchardWebPath = _orchardWebPath.Combine("src").Combine("Orchard.Web"); Log("Initialization of ASP.NET host for template web site \"{0}\":", templateName); Log(" Source location: \"{0}\"", _orchardWebPath); Log(" Temporary location: \"{0}\"", _tempSite); _knownModules = _orchardWebPath.Combine("Modules").Directories.Where(d => d.Combine("module.txt").Exists).Select(d => d.FileName).ToList(); //foreach (var filename in _knownModules) // Log("Available Module: \"{0}\"", filename); _knownThemes = _orchardWebPath.Combine("Themes").Directories.Where(d => d.Combine("theme.txt").Exists).Select(d => d.FileName).ToList(); //foreach (var filename in _knownThemes) // Log("Available Theme: \"{0}\"", filename); _knownBinAssemblies = _orchardWebPath.Combine("bin").GetFiles("*.dll").Select(f => f.FileNameWithoutExtension); //foreach (var filename in _knownBinAssemblies) // Log("Assembly in ~/bin: \"{0}\"", filename); Log("Copy files from template \"{0}\"", templateName); baseDir.Combine("Hosting").Combine(templateName) .DeepCopy(_tempSite); if (dynamicCompilationOption != DynamicCompilationOption.Enabled) { var sourceConfig = baseDir.Combine("Hosting").Combine("TemplateConfigs"); var siteConfig = _tempSite.Combine("Config"); switch (dynamicCompilationOption) { case DynamicCompilationOption.Disabled: File.Copy(sourceConfig.Combine("DisableDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config")); break; case DynamicCompilationOption.Force: File.Copy(sourceConfig.Combine("ForceDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config")); break; } } Log("Copy binaries of the \"Orchard.Web\" project"); _orchardWebPath.Combine("bin") .ShallowCopy("*.dll", _tempSite.Combine("bin")) .ShallowCopy("*.pdb", _tempSite.Combine("bin")); Log("Copy SqlCe native binaries"); if (_orchardWebPath.Combine("bin").Combine("x86").IsDirectory) { _orchardWebPath.Combine("bin").Combine("x86") .DeepCopy("*.*", _tempSite.Combine("bin").Combine("x86")); } if (_orchardWebPath.Combine("bin").Combine("amd64").IsDirectory) { _orchardWebPath.Combine("bin").Combine("amd64") .DeepCopy("*.*", _tempSite.Combine("bin").Combine("amd64")); } // Copy binaries of this project, so that remote execution of lambda // can be achieved through serialization to the ASP.NET appdomain // (see Execute(Action) method) Log("Copy Orchard.Specflow test project binaries"); baseDir.ShallowCopy( path => IsSpecFlowTestAssembly(path) && !_tempSite.Combine("bin").Combine(path.FileName).Exists, _tempSite.Combine("bin")); Log("Copy Orchard recipes"); _orchardWebPath.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes").DeepCopy("*.xml", _tempSite.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes")); StartAspNetHost(virtualDirectory); Log("ASP.NET host initialization completed in {0} sec", stopwatch.Elapsed.TotalSeconds); } private void StartAspNetHost(string virtualDirectory) { Log("Starting up ASP.NET host"); HostName = "localhost"; PhysicalDirectory = _tempSite; VirtualDirectory = virtualDirectory; _webHostAgent = (WebHostAgent)ApplicationHost.CreateApplicationHost(typeof(WebHostAgent), VirtualDirectory, PhysicalDirectory); var shuttle = new Shuttle(); Execute(() => { shuttle.CodeGenDir = HttpRuntime.CodegenDir; }); // ASP.NET folder seems to be always nested into an empty directory _codeGenDir = shuttle.CodeGenDir; _codeGenDir = _codeGenDir.Parent; Log("ASP.NET CodeGenDir: \"{0}\"", _codeGenDir); } [Serializable] public class Shuttle { public string CodeGenDir; } public void Dispose() { if (_webHostAgent != null) { _webHostAgent.Shutdown(); _webHostAgent = null; } Clean(); } private void Log(string format, params object[] args) { Trace.WriteLine(string.Format(format, args)); } public void Clean() { // Try to delete temporary files for up to ~1.2 seconds. for (int i = 0; i < 4; i++) { Log("Waiting 300msec before trying to delete temporary files"); Thread.Sleep(300); if (TryDeleteTempFiles(i == 4)) { Log("Successfully deleted all temporary files"); break; } } } private bool TryDeleteTempFiles(bool lastTry) { var result = true; if (_codeGenDir != null && _codeGenDir.Exists) { Log("Trying to delete temporary files at \"{0}\"", _codeGenDir); try { _codeGenDir.Delete(true); // <- clean as much as possible } catch (Exception e) { if (lastTry) Log("Failure: \"{0}\"", e); result = false; } } if (_tempSite != null && _tempSite.Exists) try { Log("Trying to delete temporary files at \"{0}\"", _tempSite); _tempSite.Delete(true); // <- progressively clean as much as possible } catch (Exception e) { if (lastTry) Log("failure: \"{0}\"", e); result = false; } return result; } public void CopyExtension(string extensionFolder, string extensionName, ExtensionDeploymentOptions deploymentOptions) { Log("Copy extension \"{0}\\{1}\" (options={2})", extensionFolder, extensionName, deploymentOptions); var sourceModule = _orchardWebPath.Combine(extensionFolder).Combine(extensionName); var targetModule = _tempSite.Combine(extensionFolder).Combine(extensionName); sourceModule.ShallowCopy("*.txt", targetModule); sourceModule.ShallowCopy("*.info", targetModule); if ((deploymentOptions & ExtensionDeploymentOptions.SourceCode) == ExtensionDeploymentOptions.SourceCode) { sourceModule.ShallowCopy("*.csproj", targetModule); sourceModule.DeepCopy("*.cs", targetModule); } if (sourceModule.Combine("bin").IsDirectory) { sourceModule.Combine("bin").ShallowCopy(path => IsExtensionBinaryFile(path, extensionName, deploymentOptions), targetModule.Combine("bin")); } if (sourceModule.Combine("Views").IsDirectory) sourceModule.Combine("Views").DeepCopy(targetModule.Combine("Views")); } public void CopyFile(string source, string destination) { StackTrace st = new StackTrace(true); Path origin = null; foreach(var sf in st.GetFrames()) { var sourceFile = sf.GetFileName(); if(String.IsNullOrEmpty(sourceFile)) { continue; } var testOrigin = Path.Get(sourceFile).Parent.Combine(source); if(testOrigin.Exists) { origin = testOrigin; break; } } if(origin == null) { throw new FileNotFoundException("File not found: " + source); } var target = _tempSite.Combine(destination); Directory.CreateDirectory(target.DirectoryName); File.Copy(origin, target); } private bool IsExtensionBinaryFile(Path path, string extensionName, ExtensionDeploymentOptions deploymentOptions) { bool isValidExtension = IsAssemblyFile(path); if (!isValidExtension) return false; bool isAssemblyInWebAppBin = _knownBinAssemblies.Contains(path.FileNameWithoutExtension, StringComparer.OrdinalIgnoreCase); if (isAssemblyInWebAppBin) return false; bool isExtensionAssembly = IsOrchardExtensionFile(path); bool copyExtensionAssembly = (deploymentOptions & ExtensionDeploymentOptions.CompiledAssembly) == ExtensionDeploymentOptions.CompiledAssembly; if (isExtensionAssembly && !copyExtensionAssembly) return false; return true; } private bool IsSpecFlowTestAssembly(Path path) { if (!IsAssemblyFile(path)) return false; if (IsOrchardExtensionFile(path)) return false; return true; } private bool IsAssemblyFile(Path path) { return StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".exe") || StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".dll") || StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".pdb"); } private bool IsOrchardExtensionFile(Path path) { return _knownModules.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any() || _knownThemes.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any(); } public string HostName { get; set; } public string PhysicalDirectory { get; private set; } public string VirtualDirectory { get; private set; } public string Cookies { get; set; } public void Execute(Action action) { var shuttleSend = new SerializableDelegate<Action>(action); var shuttleRecv = _webHostAgent.Execute(shuttleSend); CopyFields(shuttleRecv.Delegate.Target, shuttleSend.Delegate.Target); } private static void CopyFields<T>(T from, T to) where T : class { if (from == null || to == null) return; foreach (FieldInfo fieldInfo in from.GetType().GetFields()) { var value = fieldInfo.GetValue(from); fieldInfo.SetValue(to, value); } } } }
// // ToolkitEngine.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin 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 Xwt.Backends; using Xwt.Drawing; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Xwt { public sealed class Toolkit: IFrontend { static Toolkit currentEngine; static Toolkit nativeEngine; static Dictionary<Type, Toolkit> toolkits = new Dictionary<Type, Toolkit> (); ToolkitEngineBackend backend; ApplicationContext context; XwtTaskScheduler scheduler; ToolkitType toolkitType; ToolkitDefaults defaults; XwtSynchronizationContext synchronizationContext; int inUserCode; Queue<Action> exitActions = new Queue<Action> (); bool exitCallbackRegistered; static KnownBackend[] knownBackends = new [] { new KnownBackend { Type = ToolkitType.Gtk3, TypeName = "Xwt.GtkBackend.GtkEngine, Xwt.Gtk3" }, new KnownBackend { Type = ToolkitType.Gtk, TypeName = "Xwt.GtkBackend.GtkEngine, Xwt.Gtk" }, new KnownBackend { Type = ToolkitType.XamMac, TypeName = "Xwt.Mac.MacEngine, Xwt.XamMac" }, new KnownBackend { Type = ToolkitType.Cocoa, TypeName = "Xwt.Mac.MacEngine, Xwt.XamMac" }, new KnownBackend { Type = ToolkitType.Wpf, TypeName = "Xwt.WPFBackend.WPFEngine, Xwt.WPF" }, }; class KnownBackend { public ToolkitType Type { get; set; } public string TypeName { get; set; } public string FullTypeName { get { return TypeName + ", Version=" + typeof(Application).Assembly.GetName ().Version; } } } Dictionary<string,Image> stockIcons = new Dictionary<string, Image> (); /// <summary> /// Gets the current toolkit engine. /// </summary> /// <value>The engine currently used by Xwt.</value> public static Toolkit CurrentEngine { get { return currentEngine; } } /// <summary> /// Gets the native platform toolkit engine. /// </summary> /// <value>The native engine.</value> public static Toolkit NativeEngine { get { if (nativeEngine == null) { switch (Desktop.DesktopType) { case DesktopType.Linux: // don't mix Gtk2 and Gtk3 if (CurrentEngine != null && (CurrentEngine.Type == ToolkitType.Gtk || CurrentEngine.Type == ToolkitType.Gtk3)) nativeEngine = CurrentEngine; else if (!TryLoad (ToolkitType.Gtk3, out nativeEngine)) TryLoad (ToolkitType.Gtk, out nativeEngine); break; case DesktopType.Windows: TryLoad (ToolkitType.Wpf, out nativeEngine); break; case DesktopType.Mac: TryLoad (ToolkitType.XamMac, out nativeEngine); break; } } if (nativeEngine == null) nativeEngine = CurrentEngine; return nativeEngine; } } /// <summary> /// Gets all loaded toolkits. /// </summary> /// <value>The loaded toolkits.</value> public static IEnumerable<Toolkit> LoadedToolkits { get { return toolkits.Values; } } /// <summary> /// Gets the application context. /// </summary> /// <value>The application context.</value> internal ApplicationContext Context { get { return context; } } /// <summary> /// Gets the toolkit backend. /// </summary> /// <value>The toolkit backend.</value> internal ToolkitEngineBackend Backend { get { return backend; } } /// <summary> /// Gets the toolkit task scheduler. /// </summary> /// <value>The toolkit specific task scheduler.</value> /// <remarks> /// The Xwt task scheduler marshals every Task to the Xwt GUI thread without concurrency. /// </remarks> internal XwtTaskScheduler Scheduler { get { return scheduler; } } object IFrontend.Backend { get { return backend; } } Toolkit IFrontend.ToolkitEngine { get { return this; } } private Toolkit () { synchronizationContext = new XwtSynchronizationContext (this); context = new ApplicationContext (this); scheduler = new XwtTaskScheduler (this); } /// <summary> /// Gets a synchronization context for this toolkit. /// </summary> /// <value>The synchronization context.</value> public XwtSynchronizationContext SynchronizationContext { get { return synchronizationContext; } } /// <summary> /// Gets or sets the type of the toolkit. /// </summary> /// <value>The toolkit type.</value> public ToolkitType Type { get { return toolkitType; } internal set { toolkitType = value; } } /// <summary> /// Disposes all loaded toolkits. /// </summary> internal static void DisposeAll () { foreach (var t in toolkits.Values) t.Backend.Dispose (); } /// <summary> /// Load toolkit identified by its full type name. /// </summary> /// <param name="fullTypeName">The <see cref="Type.FullName"/> of the toolkit type.</param> public static Toolkit Load (string fullTypeName) { return Load (fullTypeName, true, true); } /// <summary> /// Load toolkit identified by its full type name. /// </summary> /// <param name="fullTypeName">The <see cref="Type.FullName"/> of the toolkit type.</param> /// <param name="isGuest">If set to <c>true</c> the toolkit is loaded as guest of another toolkit.</param> /// <param name="initializeToolkit">If set to <c>true</c> the parent toolkit is initialized.</param> internal static Toolkit Load (string fullTypeName, bool isGuest, bool initializeToolkit) { Toolkit t = new Toolkit (); if (!string.IsNullOrEmpty (fullTypeName)) { t.LoadBackend (fullTypeName, isGuest, initializeToolkit, true); var bk = knownBackends.FirstOrDefault (tk => fullTypeName.StartsWith (tk.TypeName)); if (bk != null) t.Type = bk.Type; return t; } foreach (var bk in knownBackends) { if (t.LoadBackend (bk.FullTypeName, isGuest, initializeToolkit, false)) { t.Type = bk.Type; return t; } } throw new InvalidOperationException ("Xwt engine not found"); } /// <summary> /// Load a toolkit of a specified type. /// </summary> /// <param name="type">The toolkit type.</param> public static Toolkit Load (ToolkitType type) { var et = toolkits.Values.FirstOrDefault (tk => tk.toolkitType == type); if (et != null) return et; Toolkit t = new Toolkit (); t.toolkitType = type; t.LoadBackend (GetBackendType (type), true, true, true); return t; } /// <summary> /// Tries to load a toolkit /// </summary> /// <returns><c>true</c>, the toolkit has been loaded, <c>false</c> otherwise.</returns> /// <param name="type">Toolkit type</param> /// <param name="toolkit">The loaded toolkit</param> public static bool TryLoad (ToolkitType type, out Toolkit toolkit) { var et = toolkits.Values.FirstOrDefault (tk => tk.toolkitType == type); if (et != null) { toolkit = et; return true; } Toolkit t = new Toolkit (); t.toolkitType = type; if (t.LoadBackend (GetBackendType (type), true, true, false)) { toolkit = t; return true; } toolkit = null; return false; } /// <summary> /// Gets the <see cref="Type.FullName"/> of the toolkit identified by toolkit type. /// </summary> /// <returns>The toolkit type name.</returns> /// <param name="type">The toolkit type.</param> internal static string GetBackendType (ToolkitType type) { var t = knownBackends.FirstOrDefault (tk => tk.Type == type); if (t != null) return t.FullTypeName; throw new ArgumentException ("Invalid toolkit type"); } bool LoadBackend (string type, bool isGuest, bool initializeToolkit, bool throwIfFails) { int i = type.IndexOf (','); string assembly = type.Substring (i+1).Trim (); type = type.Substring (0, i).Trim (); try { Assembly asm = Assembly.Load (assembly); if (asm != null) { Type t = asm.GetType (type); if (t != null) { backend = (ToolkitEngineBackend) Activator.CreateInstance (t); Initialize (isGuest, initializeToolkit); return true; } } } catch (Exception ex) { if (throwIfFails) throw new Exception ("Toolkit could not be loaded", ex); } if (throwIfFails) throw new Exception ("Toolkit could not be loaded"); return false; } void Initialize (bool isGuest, bool initializeToolkit) { toolkits[Backend.GetType ()] = this; backend.Initialize (this, isGuest, initializeToolkit); ContextBackendHandler = Backend.CreateBackend<ContextBackendHandler> (); GradientBackendHandler = Backend.CreateBackend<GradientBackendHandler> (); TextLayoutBackendHandler = Backend.CreateBackend<TextLayoutBackendHandler> (); FontBackendHandler = Backend.CreateBackend<FontBackendHandler> (); ClipboardBackend = Backend.CreateBackend<ClipboardBackend> (); ImageBuilderBackendHandler = Backend.CreateBackend<ImageBuilderBackendHandler> (); ImagePatternBackendHandler = Backend.CreateBackend<ImagePatternBackendHandler> (); ImageBackendHandler = Backend.CreateBackend<ImageBackendHandler> (); DrawingPathBackendHandler = Backend.CreateBackend<DrawingPathBackendHandler> (); DesktopBackend = Backend.CreateBackend<DesktopBackend> (); VectorImageRecorderContextHandler = new VectorImageRecorderContextHandler (this); KeyboardHandler = Backend.CreateBackend<KeyboardHandler> (); } /// <summary> /// Gets the toolkit backend from a loaded toolkit. /// </summary> /// <returns>The toolkit backend, or <c>null</c> if the toolkit is not loaded.</returns> /// <param name="type">The Type of the loaded toolkit.</param> internal static ToolkitEngineBackend GetToolkitBackend (Type type) { Toolkit t; if (toolkits.TryGetValue (type, out t)) return t.backend; else return null; } /// <summary> /// Set the toolkit as the active toolkit used by Xwt. /// </summary> internal void SetActive () { currentEngine = this; } /// <summary> /// Gets the defaults for the current toolkit. /// </summary> /// <value>The toolkit defaults.</value> public ToolkitDefaults Defaults { get { if (defaults == null) defaults = new ToolkitDefaults (); return defaults; } } /// <summary> /// Gets a reference to the native widget wrapped by an Xwt widget /// </summary> /// <returns>The native widget currently used by Xwt for the specific widget.</returns> /// <param name="w">The Xwt widget.</param> public object GetNativeWidget (Widget w) { ValidateObject (w); w.SetExtractedAsNative (); return backend.GetNativeWidget (w); } /// <summary> /// Gets a reference to the native window wrapped by an Xwt window /// </summary> /// <returns>The native window currently used by Xwt for the specific window, or null.</returns> /// <param name="w">The Xwt window.</param> /// <remarks> /// If the window backend belongs to a different toolkit and the current toolkit is the /// native toolkit for the current platform, GetNativeWindow will return the underlying /// native window, or null if the operation is not supported for the current toolkit. /// </remarks> public object GetNativeWindow (WindowFrame w) { return backend.GetNativeWindow (w); } /// <summary> /// Gets a reference to the native platform window used by the specified backend. /// </summary> /// <returns>The native window currently used by Xwt for the specific window, or null.</returns> /// <param name="w">The Xwt window.</param> /// <remarks> /// If the window backend belongs to a different toolkit and the current toolkit is the /// native toolkit for the current platform, GetNativeWindow will return the underlying /// native window, or null if the operation is not supported for the current toolkit. /// </remarks> public object GetNativeWindow (IWindowFrameBackend w) { return backend.GetNativeWindow (w); } /// <summary> /// Gets a reference to the image object wrapped by an XWT Image /// </summary> /// <returns>The native image object used by Xwt for the specific image.</returns> /// <param name="image">The native Image object.</param> public object GetNativeImage (Image image) { ValidateObject (image); return backend.GetNativeImage (image); } /// <summary> /// Creates a native toolkit object. /// </summary> /// <returns>A new native toolkit object.</returns> /// <typeparam name="T">The type of the object to create.</typeparam> public T CreateObject<T> () where T:new() { var oldEngine = currentEngine; try { currentEngine = this; return new T (); } finally { currentEngine = oldEngine; } } /// <summary> /// Switches the current context to the context of this toolkit /// </summary> ToolkitContext SwitchContext () { var current = System.Threading.SynchronizationContext.Current; // Store the current engine and the current context (which is not necessarily the context of the engine) var currentContext = new ToolkitContext { SynchronizationContext = current, Engine = currentEngine }; currentEngine = this; if ((current as XwtSynchronizationContext)?.TargetToolkit != this) System.Threading.SynchronizationContext.SetSynchronizationContext (SynchronizationContext); return currentContext; } struct ToolkitContext { public SynchronizationContext SynchronizationContext; public Toolkit Engine; public void Restore () { Toolkit.currentEngine = Engine; System.Threading.SynchronizationContext.SetSynchronizationContext (SynchronizationContext); } } /// <summary> /// Invokes the specified action using this toolkit. /// </summary> /// <param name="a">The action to invoke in the context of this toolkit.</param> /// <remarks> /// Invoke allows dynamic toolkit switching. It will set <see cref="CurrentEngine"/> to this toolkit and reset /// it back to its original value after the action has been executed. /// /// Invoke must be executed on the UI thread. The action will not be synchronized with the main UI thread automatically. /// </remarks> /// <returns><c>true</c> if the action has been executed sucessfully; otherwise, <c>false</c>.</returns> public bool Invoke (Action a) { ToolkitContext currentContext = SwitchContext (); try { EnterUserCode (); a (); ExitUserCode (null); return true; } catch (Exception ex) { ExitUserCode (ex); return false; } finally { currentContext.Restore (); } } public T Invoke<T> (Func<T> func) { ToolkitContext currentContext = SwitchContext (); try { EnterUserCode (); var res = func (); ExitUserCode (null); return res; } catch (Exception ex) { ExitUserCode (ex); return default (T); } finally { currentContext.Restore (); } } internal void InvokeAndThrow (Action a) { var currentContext = SwitchContext (); try { EnterUserCode (); a (); } finally { ExitUserCode (null); currentContext.Restore (); } } internal T InvokeAndThrow<T> (Func<T> func) { var currentContext = SwitchContext (); try { currentEngine = this; EnterUserCode (); return func (); } finally { ExitUserCode (null); currentContext.Restore (); } } /// <summary> /// Invokes an action after the user code has been processed. /// </summary> /// <param name="a">The action to invoke after processing user code.</param> internal void InvokePlatformCode (Action a) { int prevCount = inUserCode; inUserCode = 1; ExitUserCode (null); var currentContext = Application.MainLoop.Engine.SwitchContext (); try { a(); } finally { inUserCode = prevCount; currentContext.Restore (); } } /// <summary> /// Enters the user code. /// </summary> /// <remarks>EnterUserCode must be called before executing any user code.</remarks> internal void EnterUserCode () { inUserCode++; } /// <summary> /// Exits the user code. /// </summary> /// <param name="error">Exception thrown during user code execution, or <c>null</c></param> internal void ExitUserCode (Exception error) { if (error != null) { Invoke (delegate { Application.NotifyException (error); }); } if (inUserCode == 1 && !exitCallbackRegistered) { while (exitActions.Count > 0) { try { exitActions.Dequeue ()(); } catch (Exception ex) { Invoke (delegate { Application.NotifyException (ex); }); } } } inUserCode--; } void DispatchExitActions () { // This pair of calls will flush the exit action queue exitCallbackRegistered = false; EnterUserCode (); ExitUserCode (null); } /// <summary> /// Adds the action to the exit action queue. /// </summary> /// <param name="a">The action to invoke after processing user code.</param> internal void QueueExitAction (Action a) { exitActions.Enqueue (a); if (inUserCode == 0) { // Not in an XWT handler. This may happen when embedding XWT in another toolkit and // XWT widgets are manipulated from event handlers of the native toolkit which // are not invoked using ApplicationContext.InvokeUserCode. if (!exitCallbackRegistered) { exitCallbackRegistered = true; // Try to use a native method of queuing exit actions Toolkit.CurrentEngine.Backend.InvokeBeforeMainLoop (DispatchExitActions); } } } /// <summary> /// Gets a value indicating whether the GUI Thread is currently executing user code. /// </summary> /// <value><c>true</c> if in user code; otherwise, <c>false</c>.</value> public bool InUserCode { get { return inUserCode > 0; } } /// <summary> /// Wraps a native window into an Xwt window object. /// </summary> /// <returns>An Xwt window with the specified native window backend.</returns> /// <param name="nativeWindow">The native window.</param> public WindowFrame WrapWindow (object nativeWindow) { if (nativeWindow == null) return null; return new NativeWindowFrame (backend.GetBackendForWindow (nativeWindow)); } /// <summary> /// Wraps a native widget into an Xwt widget object. /// </summary> /// <returns>An Xwt widget with the specified native widget backend.</returns> /// <param name="nativeWidget">The native widget.</param> public Widget WrapWidget (object nativeWidget, NativeWidgetSizing preferredSizing = NativeWidgetSizing.External, bool reparent = true) { var externalWidget = nativeWidget as Widget; if (externalWidget != null) { if (externalWidget.Surface.ToolkitEngine == this) return externalWidget; nativeWidget = externalWidget.Surface.ToolkitEngine.GetNativeWidget (externalWidget); } var embedded = CreateObject<EmbeddedNativeWidget> (); embedded.Initialize (nativeWidget, externalWidget, preferredSizing, reparent); return embedded; } /// <summary> /// Wraps a native image object into an Xwt image instance. /// </summary> /// <returns>The Xwt image containing the native image.</returns> /// <param name="nativeImage">The native image.</param> public Image WrapImage (object nativeImage) { return new Image (backend.GetBackendForImage (nativeImage), this); } /// <summary> /// Wraps a native drawing context into an Xwt context object. /// </summary> /// <returns>The Xwt drawing context.</returns> /// <param name="nativeWidget">The native widget to use for drawing.</param> /// <param name="nativeContext">The native drawing context.</param> public Context WrapContext (object nativeWidget, object nativeContext) { return new Context (backend.GetBackendForContext (nativeWidget, nativeContext), this); } public Accessibility.Accessible WrapAccessible (object nativeAccessibleObject) { return new Accessibility.Accessible (nativeAccessibleObject); } /// <summary> /// Validates that the backend of an Xwt component belongs to the currently loaded toolkit. /// </summary> /// <returns>The validated Xwt object.</returns> /// <param name="obj">The Xwt object.</param> /// <exception cref="InvalidOperationException">The component belongs to a different toolkit</exception> public object ValidateObject (object obj) { if (obj is Image) ((Image)obj).InitForToolkit (this); else if (obj is TextLayout) ((TextLayout)obj).InitForToolkit (this); else if (obj is Font) { var font = (Font)obj; // If the font instance is a system font, we swap instances // to not corrupt the backend of the singletons if (font.ToolkitEngine != this) { var fbh = font.ToolkitEngine.FontBackendHandler; if (font.Family == fbh.SystemFont.Family) font = FontBackendHandler.SystemFont.WithSettings (font); if (font.Family == fbh.SystemMonospaceFont.Family) font = FontBackendHandler.SystemMonospaceFont.WithSettings (font); if (font.Family == fbh.SystemSansSerifFont.Family) font = FontBackendHandler.SystemSansSerifFont.WithSettings (font); if (font.Family == fbh.SystemSerifFont.Family) font = FontBackendHandler.SystemSerifFont.WithSettings (font); } font.InitForToolkit (this); obj = font; } else if (obj is Gradient) { ((Gradient)obj).InitForToolkit (this); } else if (obj is IFrontend) { if (((IFrontend)obj).ToolkitEngine != this) throw new InvalidOperationException ("Object belongs to a different toolkit"); } return obj; } /// <summary> /// Gets a toolkit backend of an Xwt component and validates /// that it belongs to the currently loaded toolkit. /// </summary> /// <returns>The toolkit backend of the Xwt component.</returns> /// <param name="obj">The Xwt component.</param> /// <exception cref="InvalidOperationException">The component belongs to a different toolkit</exception> public object GetSafeBackend (object obj) { return GetBackend (ValidateObject (obj)); } /// <summary> /// Gets a toolkit backend currently used by an Xwt component. /// </summary> /// <returns>The toolkit backend of the Xwt component.</returns> /// <param name="obj">The Xwt component.</param> /// <exception cref="InvalidOperationException">The component does not have a backend</exception> public static object GetBackend (object obj) { if (obj is IFrontend) return ((IFrontend)obj).Backend; else if (obj == null) return null; else throw new InvalidOperationException ("Object doesn't have a backend"); } /// <summary> /// Gets the bounds of a native widget in screen coordinates. /// </summary> /// <returns>The screen bounds relative to <see cref="P:Xwt.Desktop.Bounds"/>.</returns> /// <param name="nativeWidget">The native widget.</param> /// <exception cref="ArgumentNullException"><paramref name="nativeWidget"/> is <c>null</c>.</exception> /// <exception cref="NotSupportedException">This toolkit does not support this operation.</exception> /// <exception cref="InvalidOperationException"><paramref name="nativeWidget"/> does not belong to this toolkit.</exception> public Rectangle GetScreenBounds (object nativeWidget) { if (nativeWidget == null) throw new ArgumentNullException (nameof(nativeWidget)); return backend.GetScreenBounds(nativeWidget); } /// <summary> /// Creates an Xwt frontend for a backend. /// </summary> /// <returns>The Xwt frontend.</returns> /// <param name="ob">The toolkit backend.</param> /// <typeparam name="T">The frontend Type.</typeparam> public T CreateFrontend<T> (object ob) { throw new NotImplementedException (); } /// <summary> /// Renders the widget into an Xwt Image. /// </summary> /// <returns>An Xwt Image containing the rendered bitmap.</returns> /// <param name="widget">The Widget to render.</param> public Image RenderWidget (Widget widget) { return new Image (backend.RenderWidget (widget), this); } /// <summary> /// Renders an image to the provided native drawing context /// </summary> /// <param name="nativeWidget">The native widget.</param> /// <param name="nativeContext">The native context.</param> /// <param name="img">The Image to render.</param> /// <param name="x">The destinate x coordinate.</param> /// <param name="y">The destinate y coordinate.</param> public void RenderImage (object nativeWidget, object nativeContext, Image img, double x, double y) { ValidateObject (img); img.GetFixedSize (); // Ensure that it has a size backend.RenderImage (nativeWidget, nativeContext, img.GetImageDescription (this), x, y); } /// <summary> /// Gets the information about Xwt features supported by the toolkit. /// </summary> /// <value>The supported features.</value> public ToolkitFeatures SupportedFeatures { get { return backend.SupportedFeatures; } } /// <summary> /// Registers a backend for an Xwt backend interface. /// </summary> /// <typeparam name="TBackend">The backend Type</typeparam> /// <typeparam name="TImplementation">The Xwt interface implemented by the backend.</typeparam> public void RegisterBackend<TBackend, TImplementation> () where TImplementation: TBackend { backend.RegisterBackend<TBackend, TImplementation> (); } /// <summary> /// Gets the stock icon identified by the stock id. /// </summary> /// <returns>The stock icon.</returns> /// <param name="id">The stock identifier.</param> internal Image GetStockIcon (string id) { Image img; if (!stockIcons.TryGetValue (id, out img)) stockIcons [id] = img = ImageBackendHandler.GetStockIcon (id); return img; } internal ContextBackendHandler ContextBackendHandler; internal GradientBackendHandler GradientBackendHandler; internal TextLayoutBackendHandler TextLayoutBackendHandler; internal FontBackendHandler FontBackendHandler; internal ClipboardBackend ClipboardBackend; internal ImageBuilderBackendHandler ImageBuilderBackendHandler; internal ImagePatternBackendHandler ImagePatternBackendHandler; internal ImageBackendHandler ImageBackendHandler; internal DrawingPathBackendHandler DrawingPathBackendHandler; internal DesktopBackend DesktopBackend; internal VectorImageRecorderContextHandler VectorImageRecorderContextHandler; internal KeyboardHandler KeyboardHandler; } class NativeWindowFrame: WindowFrame { public NativeWindowFrame (IWindowFrameBackend backend) { BackendHost.SetCustomBackend (backend); } } [Flags] public enum ToolkitFeatures: int { /// <summary> /// Widget opacity/transparancy. /// </summary> WidgetOpacity = 1, /// <summary> /// Window opacity/transparancy. /// </summary> WindowOpacity = 2, /// <summary> /// All available features /// </summary> All = WidgetOpacity | WindowOpacity } }
using System; using System.Data.Linq; using System.Data.SqlTypes; using System.IO; using System.Linq.Expressions; using System.Text; using System.Xml; using LinqToDB.Extensions; namespace LinqToDB.DataProvider.SqlServer { using Common; using Expressions; using Mapping; using SqlQuery; public class SqlServerMappingSchema : MappingSchema { public SqlServerMappingSchema() : base(ProviderName.SqlServer) { SetConvertExpression<SqlXml,XmlReader>( s => s.IsNull ? DefaultValue<XmlReader>.Value : s.CreateReader(), s => s.CreateReader()); SetConvertExpression<string,SqlXml>(s => new SqlXml(new MemoryStream(Encoding.UTF8.GetBytes(s)))); AddScalarType(typeof(SqlBinary), SqlBinary. Null, true, DataType.VarBinary); AddScalarType(typeof(SqlBoolean), SqlBoolean. Null, true, DataType.Boolean); AddScalarType(typeof(SqlByte), SqlByte. Null, true, DataType.Byte); AddScalarType(typeof(SqlDateTime), SqlDateTime.Null, true, DataType.DateTime); AddScalarType(typeof(SqlDecimal), SqlDecimal. Null, true, DataType.Decimal); AddScalarType(typeof(SqlDouble), SqlDouble. Null, true, DataType.Double); AddScalarType(typeof(SqlGuid), SqlGuid. Null, true, DataType.Guid); AddScalarType(typeof(SqlInt16), SqlInt16. Null, true, DataType.Int16); AddScalarType(typeof(SqlInt32), SqlInt32. Null, true, DataType.Int32); AddScalarType(typeof(SqlInt64), SqlInt64. Null, true, DataType.Int64); AddScalarType(typeof(SqlMoney), SqlMoney. Null, true, DataType.Money); AddScalarType(typeof(SqlSingle), SqlSingle. Null, true, DataType.Single); AddScalarType(typeof(SqlString), SqlString. Null, true, DataType.NVarChar); AddScalarType(typeof(SqlXml), SqlXml. Null, true, DataType.Xml); try { foreach (var typeInfo in new[] { new { Type = SqlServerTools.SqlHierarchyIdType, Name = "SqlHierarchyId" }, new { Type = SqlServerTools.SqlGeographyType, Name = "SqlGeography" }, new { Type = SqlServerTools.SqlGeometryType, Name = "SqlGeometry" }, }) { var type = typeInfo.Type ?? Type.GetType("Microsoft.SqlServer.Types.{0}, Microsoft.SqlServer.Types".Args(typeInfo.Name)); if (type == null) continue; var p = type.GetPropertyEx("Null"); var l = Expression.Lambda<Func<object>>( Expression.Convert(Expression.Property(null, p), typeof(object))); var nullValue = l.Compile()(); AddScalarType(type, nullValue, true, DataType.Udt); SqlServerDataProvider.SetUdtType(type, typeInfo.Name.Substring(3).ToLower()); } } catch { } SetValueToSqlConverter(typeof(String), (sb,dt,v) => ConvertStringToSql (sb, dt, v.ToString())); SetValueToSqlConverter(typeof(Char), (sb,dt,v) => ConvertCharToSql (sb, dt, (char)v)); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql (sb, (DateTime)v)); SetValueToSqlConverter(typeof(TimeSpan), (sb,dt,v) => ConvertTimeSpanToSql (sb, dt, (TimeSpan)v)); SetValueToSqlConverter(typeof(DateTimeOffset), (sb,dt,v) => ConvertDateTimeOffsetToSql(sb, dt, (DateTimeOffset)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), int.MaxValue)); } internal static SqlServerMappingSchema Instance = new SqlServerMappingSchema(); public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { if (@from != to && @from.FullName == to.FullName && @from.Namespace == "Microsoft.SqlServer.Types") { var p = Expression.Parameter(@from); return Expression.Lambda( Expression.Call(to, "Parse", new Type[0], Expression.New( MemberHelper.ConstructorOf(() => new SqlString("")), Expression.Call( Expression.Convert(p, typeof(object)), "ToString", new Type[0]))), p); } return base.TryGetConvertExpression(@from, to); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("char(") .Append(value) .Append(')') ; } static void ConvertStringToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, string value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertStringToSql(stringBuilder, "+", start, AppendConversion, value); } static void ConvertCharToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, char value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertCharToSql(stringBuilder, start, AppendConversion, value); } static void ConvertDateTimeToSql(StringBuilder stringBuilder, DateTime value) { var format = value.Millisecond == 0 ? value.Hour == 0 && value.Minute == 0 && value.Second == 0 ? "yyyy-MM-dd" : "yyyy-MM-ddTHH:mm:ss" : "yyyy-MM-ddTHH:mm:ss.fff"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } static void ConvertTimeSpanToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, TimeSpan value) { if (sqlDataType.DataType == DataType.Int64) { stringBuilder.Append(value.Ticks); } else { var format = value.Days > 0 ? value.Milliseconds > 0 ? "d\\.hh\\:mm\\:ss\\.fff" : "d\\.hh\\:mm\\:ss" : value.Milliseconds > 0 ? "hh\\:mm\\:ss\\.fff" : "hh\\:mm\\:ss"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } } static void ConvertDateTimeOffsetToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, DateTimeOffset value) { var format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; switch (sqlDataType.Precision ?? sqlDataType.Scale) { case 0 : format = "'{0:yyyy-MM-dd HH:mm:ss zzz}'"; break; case 1 : format = "'{0:yyyy-MM-dd HH:mm:ss.f zzz}'"; break; case 2 : format = "'{0:yyyy-MM-dd HH:mm:ss.ff zzz}'"; break; case 3 : format = "'{0:yyyy-MM-dd HH:mm:ss.fff zzz}'"; break; case 4 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffff zzz}'"; break; case 5 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffff zzz}'"; break; case 6 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffffff zzz}'"; break; case 7 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; break; } stringBuilder.AppendFormat(format, value); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } } public class SqlServer2000MappingSchema : MappingSchema { public SqlServer2000MappingSchema() : base(ProviderName.SqlServer2000, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2005MappingSchema : MappingSchema { public SqlServer2005MappingSchema() : base(ProviderName.SqlServer2005, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2008MappingSchema : MappingSchema { public SqlServer2008MappingSchema() : base(ProviderName.SqlServer2008, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2012MappingSchema : MappingSchema { public SqlServer2012MappingSchema() : base(ProviderName.SqlServer2012, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } }
// LzmaEncoder.cs using System; using System.IO; using YGOSharp.SevenZip.Compress.LZ; using YGOSharp.SevenZip.Compress.RangeCoder; namespace YGOSharp.SevenZip.Compress.LZMA { public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties { enum EMatchFinderType { BT2, BT4 }; const UInt32 kIfinityPrice = 0xFFFFFFF; static Byte[] g_FastPos = new Byte[1 << 11]; static Encoder() { const Byte kFastSlots = 22; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) { UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); for (UInt32 j = 0; j < k; j++, c++) g_FastPos[c] = slotFast; } } static UInt32 GetPosSlot(UInt32 pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) return (UInt32)(g_FastPos[pos >> 10] + 20); return (UInt32)(g_FastPos[pos >> 20] + 40); } static UInt32 GetPosSlot2(UInt32 pos) { if (pos < (1 << 17)) return (UInt32)(g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) return (UInt32)(g_FastPos[pos >> 16] + 32); return (UInt32)(g_FastPos[pos >> 26] + 52); } Base.State _state = new Base.State(); Byte _previousByte; UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; void BaseInit() { _state.Init(); _previousByte = 0; for (UInt32 i = 0; i < Base.kNumRepDistances; i++) _repDistances[i] = 0; } const int kDefaultDictionaryLogSize = 22; const UInt32 kNumFastBytesDefault = 0x20; class LiteralEncoder { public struct Encoder2 { BitEncoder[] m_Encoders; public void Create() { m_Encoders = new BitEncoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) { uint context = 1; for (int i = 7; i >= 0; i--) { uint bit = (uint)((symbol >> i) & 1); m_Encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } } public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) { uint context = 1; bool same = true; for (int i = 7; i >= 0; i--) { uint bit = (uint)((symbol >> i) & 1); uint state = context; if (same) { uint matchBit = (uint)((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } m_Encoders[state].Encode(rangeEncoder, bit); context = (context << 1) | bit; } } public uint GetPrice(bool matchMode, byte matchByte, byte symbol) { uint price = 0; uint context = 1; int i = 7; if (matchMode) { for (; i >= 0; i--) { uint matchBit = (uint)(matchByte >> i) & 1; uint bit = (uint)(symbol >> i) & 1; price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); context = (context << 1) | bit; if (matchBit != bit) { i--; break; } } } for (; i >= 0; i--) { uint bit = (uint)(symbol >> i) & 1; price += m_Encoders[context].GetPrice(bit); context = (context << 1) | bit; } return price; } } Encoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } } class LenEncoder { BitEncoder _choice = new BitEncoder(); BitEncoder _choice2 = new BitEncoder(); BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } public void Init(UInt32 numPosStates) { _choice.Init(); _choice2.Init(); for (UInt32 posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) { if (symbol < Base.kNumLowLenSymbols) { _choice.Encode(rangeEncoder, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { symbol -= Base.kNumLowLenSymbols; _choice.Encode(rangeEncoder, 1); if (symbol < Base.kNumMidLenSymbols) { _choice2.Encode(rangeEncoder, 0); _midCoder[posState].Encode(rangeEncoder, symbol); } else { _choice2.Encode(rangeEncoder, 1); _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); } } } public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) { UInt32 a0 = _choice.GetPrice0(); UInt32 a1 = _choice.GetPrice1(); UInt32 b0 = a1 + _choice2.GetPrice0(); UInt32 b1 = a1 + _choice2.GetPrice1(); UInt32 i = 0; for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); } }; const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; class LenPriceTableEncoder : LenEncoder { UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; UInt32 _tableSize; UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } public UInt32 GetPrice(UInt32 symbol, UInt32 posState) { return _prices[posState * Base.kNumLenSymbols + symbol]; } void UpdateTable(UInt32 posState) { SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(UInt32 numPosStates) { for (UInt32 posState = 0; posState < numPosStates; posState++) UpdateTable(posState); } public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) { base.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) UpdateTable(posState); } } const UInt32 kNumOpts = 1 << 12; class Optimal { public Base.State State; public bool Prev1IsChar; public bool Prev2; public UInt32 PosPrev2; public UInt32 BackPrev2; public UInt32 Price; public UInt32 PosPrev; public UInt32 BackPrev; public UInt32 Backs0; public UInt32 Backs1; public UInt32 Backs2; public UInt32 Backs3; public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } public bool IsShortRep() { return (BackPrev == 0); } }; Optimal[] _optimum = new Optimal[kNumOpts]; IMatchFinder _matchFinder; RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); BitEncoder[] _isMatch = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitEncoder[] _isRep = new BitEncoder[Base.kNumStates]; BitEncoder[] _isRepG0 = new BitEncoder[Base.kNumStates]; BitEncoder[] _isRepG1 = new BitEncoder[Base.kNumStates]; BitEncoder[] _isRepG2 = new BitEncoder[Base.kNumStates]; BitEncoder[] _isRep0Long = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; BitEncoder[] _posEncoders = new BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); LiteralEncoder _literalEncoder = new LiteralEncoder(); UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; UInt32 _numFastBytes = kNumFastBytesDefault; UInt32 _longestMatchLength; UInt32 _numDistancePairs; UInt32 _additionalOffset; UInt32 _optimumEndIndex; UInt32 _optimumCurrentIndex; bool _longestMatchWasFound; UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; UInt32 _alignPriceCount; UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); int _posStateBits = 2; UInt32 _posStateMask = (4 - 1); int _numLiteralPosStateBits; int _numLiteralContextBits = 3; UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); UInt32 _dictionarySizePrev = 0xFFFFFFFF; UInt32 _numFastBytesPrev = 0xFFFFFFFF; Int64 nowPos64; bool _finished; Stream _inStream; EMatchFinderType _matchFinderType = EMatchFinderType.BT4; bool _writeEndMark; bool _needReleaseMFStream; void Create() { if (_matchFinder == null) { BinTree bt = new BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderType.BT2) numHashBytes = 2; bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return; _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; } public Encoder() { for (int i = 0; i < kNumOpts; i++) _optimum[i] = new Optimal(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); } void SetWriteEndMarkerMode(bool writeEndMarker) { _writeEndMark = writeEndMarker; } void Init() { BaseInit(); _rangeEncoder.Init(); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= _posStateMask; j++) { uint complexState = (i << Base.kNumPosStatesBitsMax) + j; _isMatch[complexState].Init(); _isRep0Long[complexState].Init(); } _isRep[i].Init(); _isRepG0[i].Init(); _isRepG1[i].Init(); _isRepG2[i].Init(); } _literalEncoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) _posEncoders[i].Init(); _lenEncoder.Init((UInt32)1 << _posStateBits); _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; } void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) { lenRes = 0; numDistancePairs = _matchFinder.GetMatches(_matchDistances); if (numDistancePairs > 0) { lenRes = _matchDistances[numDistancePairs - 2]; if (lenRes == _numFastBytes) lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], Base.kMatchMaxLen - lenRes); } _additionalOffset++; } void MovePos(UInt32 num) { if (num > 0) { _matchFinder.Skip(num); _additionalOffset += num; } } UInt32 GetRepLen1Price(Base.State state, UInt32 posState) { return _isRepG0[state.Index].GetPrice0() + _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); } UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) { UInt32 price; if (repIndex == 0) { price = _isRepG0[state.Index].GetPrice0(); price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); } else { price = _isRepG0[state.Index].GetPrice1(); if (repIndex == 1) price += _isRepG1[state.Index].GetPrice0(); else { price += _isRepG1[state.Index].GetPrice1(); price += _isRepG2[state.Index].GetPrice(repIndex - 2); } } return price; } UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) { UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) { UInt32 price; UInt32 lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } UInt32 Backward(out UInt32 backRes, UInt32 cur) { _optimumEndIndex = cur; UInt32 posMem = _optimum[cur].PosPrev; UInt32 backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } UInt32 posPrev = posMem; UInt32 backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } UInt32[] reps = new UInt32[Base.kNumRepDistances]; UInt32[] repLens = new UInt32[Base.kNumRepDistances]; UInt32 GetOptimum(UInt32 position, out UInt32 backRes) { if (_optimumEndIndex != _optimumCurrentIndex) { UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; backRes = _optimum[_optimumCurrentIndex].BackPrev; _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; return lenRes; } _optimumCurrentIndex = _optimumEndIndex = 0; UInt32 lenMain, numDistancePairs; if (!_longestMatchWasFound) { ReadMatchDistances(out lenMain, out numDistancePairs); } else { lenMain = _longestMatchLength; numDistancePairs = _numDistancePairs; _longestMatchWasFound = false; } UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; if (numAvailableBytes < 2) { backRes = 0xFFFFFFFF; return 1; } if (numAvailableBytes > Base.kMatchMaxLen) numAvailableBytes = Base.kMatchMaxLen; UInt32 repMaxIndex = 0; UInt32 i; for (i = 0; i < Base.kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; UInt32 lenRes = repLens[repMaxIndex]; MovePos(lenRes - 1); return lenRes; } if (lenMain >= _numFastBytes) { backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; MovePos(lenMain - 1); return lenMain; } Byte currentByte = _matchFinder.GetIndexByte(0 - 1); Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { backRes = 0xFFFFFFFF; return 1; } _optimum[0].State = _state; UInt32 posState = (position & _posStateMask); _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); _optimum[1].MakeAsChar(); UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); if (matchByte == currentByte) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if (shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); if(lenEnd < 2) { backRes = _optimum[1].BackPrev; return 1; } _optimum[1].PosPrev = 0; _optimum[0].Backs0 = reps[0]; _optimum[0].Backs1 = reps[1]; _optimum[0].Backs2 = reps[2]; _optimum[0].Backs3 = reps[3]; UInt32 len = lenEnd; do _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { UInt32 repLen = repLens[i]; if (repLen < 2) continue; UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); Optimal optimum = _optimum[repLen]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } while (--repLen >= 2); } UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= lenMain) { UInt32 offs = 0; while (len > _matchDistances[offs]) offs += 2; for (; ; len++) { UInt32 distance = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); Optimal optimum = _optimum[len]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = distance + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (len == _matchDistances[offs]) { offs += 2; if (offs == numDistancePairs) break; } } } UInt32 cur = 0; while (true) { cur++; if (cur == lenEnd) return Backward(out backRes, cur); UInt32 newLen; ReadMatchDistances(out newLen, out numDistancePairs); if (newLen >= _numFastBytes) { _numDistancePairs = numDistancePairs; _longestMatchLength = newLen; _longestMatchWasFound = true; return Backward(out backRes, cur); } position++; UInt32 posPrev = _optimum[cur].PosPrev; Base.State state; if (_optimum[cur].Prev1IsChar) { posPrev--; if (_optimum[cur].Prev2) { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } else state = _optimum[posPrev].State; state.UpdateChar(); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) state.UpdateShortRep(); else state.UpdateChar(); } else { UInt32 pos; if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) { posPrev = _optimum[cur].PosPrev2; pos = _optimum[cur].BackPrev2; state.UpdateRep(); } else { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) { if (pos == 0) { reps[0] = opt.Backs0; reps[1] = opt.Backs1; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 1) { reps[0] = opt.Backs1; reps[1] = opt.Backs0; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 2) { reps[0] = opt.Backs2; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs3; } else { reps[0] = opt.Backs3; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } else { reps[0] = (pos - Base.kNumRepDistances); reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } _optimum[cur].State = state; _optimum[cur].Backs0 = reps[0]; _optimum[cur].Backs1 = reps[1]; _optimum[cur].Backs2 = reps[2]; _optimum[cur].Backs3 = reps[3]; UInt32 curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); posState = (position & _posStateMask); UInt32 curAnd1Price = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). GetPrice(!state.IsCharState(), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; bool nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); if (matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if (shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); nextIsChar = true; } } UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull); numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateChar(); UInt32 posStateNext = (position + 1) & _posStateMask; UInt32 nextRepMatchPrice = curAnd1Price + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + _isRep[state2.Index].GetPrice1(); { UInt32 offset = cur + 1 + lenTest2; while (lenEnd < offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } UInt32 startLen = 2; // speed optimization for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) { UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) continue; UInt32 lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while(--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; // if (_maxMode) if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateRep(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, _matchFinder.GetIndexByte((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1)), _matchFinder.GetIndexByte((Int32)lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); // for(; lenTest2 >= 2; lenTest2--) { UInt32 offset = lenTest + 1 + lenTest2; while(lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } if (newLen > numAvailableBytes) { newLen = numAvailableBytes; for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } if (newLen >= startLen) { normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); while (lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 offs = 0; while (startLen > _matchDistances[offs]) offs += 2; for (UInt32 lenTest = startLen; ; lenTest++) { UInt32 curBack = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (lenTest == _matchDistances[offs]) { if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateMatch(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = curAndLenPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). GetPrice(true, _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), _matchFinder.GetIndexByte((Int32)lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); UInt32 offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + Base.kNumRepDistances; } } } offs += 2; if (offs == numDistancePairs) break; } } } } } bool ChangePair(UInt32 smallDist, UInt32 bigDist) { const int kDif = 7; return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); } void WriteEndMarker(UInt32 posState) { if (!_writeEndMark) return; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); _isRep[_state.Index].Encode(_rangeEncoder, 0); _state.UpdateMatch(); UInt32 len = Base.kMatchMinLen; _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; UInt32 posReduced = (((UInt32)1) << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } void Flush(UInt32 nowPos) { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); _rangeEncoder.FlushStream(); } public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) { inSize = 0; outSize = 0; finished = true; if (_inStream != null) { _matchFinder.SetStream(_inStream); _matchFinder.Init(); _needReleaseMFStream = true; _inStream = null; if (_trainSize > 0) _matchFinder.Skip(_trainSize); } if (_finished) return; _finished = true; Int64 progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } UInt32 len, numDistancePairs; // it's not used ReadMatchDistances(out len, out numDistancePairs); UInt32 posState = (UInt32)(nowPos64) & _posStateMask; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); _state.UpdateChar(); Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } while (true) { UInt32 pos; UInt32 len = GetOptimum((UInt32)nowPos64, out pos); UInt32 posState = ((UInt32)nowPos64) & _posStateMask; UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == 0xFFFFFFFF) { _isMatch[complexState].Encode(_rangeEncoder, 0); Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); if (!_state.IsCharState()) { Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else subCoder.Encode(_rangeEncoder, curByte); _previousByte = curByte; _state.UpdateChar(); } else { _isMatch[complexState].Encode(_rangeEncoder, 1); if (pos < Base.kNumRepDistances) { _isRep[_state.Index].Encode(_rangeEncoder, 1); if (pos == 0) { _isRepG0[_state.Index].Encode(_rangeEncoder, 0); if (len == 1) _isRep0Long[complexState].Encode(_rangeEncoder, 0); else _isRep0Long[complexState].Encode(_rangeEncoder, 1); } else { _isRepG0[_state.Index].Encode(_rangeEncoder, 1); if (pos == 1) _isRepG1[_state.Index].Encode(_rangeEncoder, 0); else { _isRepG1[_state.Index].Encode(_rangeEncoder, 1); _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); } } if (len == 1) _state.UpdateShortRep(); else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); _state.UpdateRep(); } UInt32 distance = _repDistances[pos]; if (pos != 0) { for (UInt32 i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _isRep[_state.Index].Encode(_rangeEncoder, 0); _state.UpdateMatch(); _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); pos -= Base.kNumRepDistances; UInt32 posSlot = GetPosSlot(pos); UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); if (posSlot >= Base.kStartPosModelIndex) { int footerBits = (int)((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); UInt32 posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } } UInt32 distance = pos; for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; _matchPriceCount++; } _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); } _additionalOffset -= len; nowPos64 += len; if (_additionalOffset == 0) { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) FillDistancesPrices(); if (_alignPriceCount >= Base.kAlignTableSize) FillAlignPrices(); inSize = nowPos64; outSize = _rangeEncoder.GetProcessedSizeAdd(); if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; finished = false; return; } } } } void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { _matchFinder.ReleaseStream(); _needReleaseMFStream = false; } } void SetOutStream(Stream outStream) { _rangeEncoder.SetStream(outStream); } void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } void SetStreams(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize) { _inStream = inStream; _finished = false; Create(); SetOutStream(outStream); Init(); // if (!_fastMode) { FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); nowPos64 = 0; } public void Code(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { _needReleaseMFStream = false; try { SetStreams(inStream, outStream, inSize, outSize); while (true) { Int64 processedInSize; Int64 processedOutSize; bool finished; CodeOneBlock(out processedInSize, out processedOutSize, out finished); if (finished) return; if (progress != null) { progress.SetProgress(processedInSize, processedOutSize); } } } finally { ReleaseStreams(); } } const int kPropSize = 5; Byte[] properties = new Byte[kPropSize]; public void WriteCoderProperties(Stream outStream) { properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); outStream.Write(properties, 0, kPropSize); } UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; UInt32 _matchPriceCount; void FillDistancesPrices() { for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { UInt32 posSlot = GetPosSlot(i); int footerBits = (int)((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { UInt32 posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; UInt32 st = (lenToPosState << Base.kNumPosSlotBits); for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << BitEncoder.kNumBitPriceShiftBits); UInt32 st2 = lenToPosState * Base.kNumFullDistances; UInt32 i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; for (; i < Base.kNumFullDistances; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } _matchPriceCount = 0; } void FillAlignPrices() { for (UInt32 i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = 0; } static string[] kMatchFinderIDs = { "BT2", "BT4" }; static int FindMatchFinder(string s) { for (int m = 0; m < kMatchFinderIDs.Length; m++) if (s == kMatchFinderIDs[m]) return m; return -1; } public void SetCoderProperties(CoderPropID[] propIDs, object[] properties) { for (UInt32 i = 0; i < properties.Length; i++) { object prop = properties[i]; switch (propIDs[i]) { case CoderPropID.NumFastBytes: { if (!(prop is Int32)) throw new InvalidParamException(); Int32 numFastBytes = (Int32)prop; if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) throw new InvalidParamException(); _numFastBytes = (UInt32)numFastBytes; break; } case CoderPropID.Algorithm: { /* if (!(prop is Int32)) throw new InvalidParamException(); Int32 maximize = (Int32)prop; _fastMode = (maximize == 0); _maxMode = (maximize >= 2); */ break; } case CoderPropID.MatchFinder: { if (!(prop is String)) throw new InvalidParamException(); EMatchFinderType matchFinderIndexPrev = _matchFinderType; int m = FindMatchFinder(((string)prop).ToUpper()); if (m < 0) throw new InvalidParamException(); _matchFinderType = (EMatchFinderType)m; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = 0xFFFFFFFF; _matchFinder = null; } break; } case CoderPropID.DictionarySize: { const int kDicLogSizeMaxCompress = 30; if (!(prop is Int32)) throw new InvalidParamException(); ; Int32 dictionarySize = (Int32)prop; if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) throw new InvalidParamException(); _dictionarySize = (UInt32)dictionarySize; int dicLogSize; for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) if (dictionarySize <= ((UInt32)(1) << dicLogSize)) break; _distTableSize = (UInt32)dicLogSize * 2; break; } case CoderPropID.PosStateBits: { if (!(prop is Int32)) throw new InvalidParamException(); Int32 v = (Int32)prop; if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) throw new InvalidParamException(); _posStateBits = v; _posStateMask = (((UInt32)1) << _posStateBits) - 1; break; } case CoderPropID.LitPosBits: { if (!(prop is Int32)) throw new InvalidParamException(); Int32 v = (Int32)prop; if (v < 0 || v > Base.kNumLitPosStatesBitsEncodingMax) throw new InvalidParamException(); _numLiteralPosStateBits = v; break; } case CoderPropID.LitContextBits: { if (!(prop is Int32)) throw new InvalidParamException(); Int32 v = (Int32)prop; if (v < 0 || v > Base.kNumLitContextBitsMax) throw new InvalidParamException(); ; _numLiteralContextBits = v; break; } case CoderPropID.EndMarker: { if (!(prop is Boolean)) throw new InvalidParamException(); SetWriteEndMarkerMode((Boolean)prop); break; } default: throw new InvalidParamException(); } } } uint _trainSize; public void SetTrainSize(uint trainSize) { _trainSize = trainSize; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.DrawingCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media { sealed public partial class DrawingCollection : System.Windows.Media.Animation.Animatable, System.Collections.IList, System.Collections.ICollection, IList<Drawing>, ICollection<Drawing>, IEnumerable<Drawing>, System.Collections.IEnumerable { #region Methods and constructors public void Add(Drawing value) { } public void Clear() { } public DrawingCollection Clone() { return default(DrawingCollection); } protected override void CloneCore(System.Windows.Freezable source) { } public DrawingCollection CloneCurrentValue() { return default(DrawingCollection); } protected override void CloneCurrentValueCore(System.Windows.Freezable source) { } public bool Contains(Drawing value) { return default(bool); } public void CopyTo(Drawing[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } public DrawingCollection(IEnumerable<Drawing> collection) { } public DrawingCollection(int capacity) { } public DrawingCollection() { } protected override bool FreezeCore(bool isChecking) { return default(bool); } protected override void GetAsFrozenCore(System.Windows.Freezable source) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source) { } public DrawingCollection.Enumerator GetEnumerator() { return default(DrawingCollection.Enumerator); } public int IndexOf(Drawing value) { return default(int); } public void Insert(int index, Drawing value) { } public bool Remove(Drawing value) { return default(bool); } public void RemoveAt(int index) { } IEnumerator<Drawing> System.Collections.Generic.IEnumerable<System.Windows.Media.Drawing>.GetEnumerator() { return default(IEnumerator<Drawing>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(Object value) { return default(int); } bool System.Collections.IList.Contains(Object value) { return default(bool); } int System.Collections.IList.IndexOf(Object value) { return default(int); } void System.Collections.IList.Insert(int index, Object value) { } void System.Collections.IList.Remove(Object value) { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public Drawing this [int index] { get { return default(Drawing); } set { } } bool System.Collections.Generic.ICollection<System.Windows.Media.Drawing>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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; namespace Spine { public class Animation { internal ExposedList<Timeline> timelines; internal float duration; internal String name; public String Name { get { return name; } } public ExposedList<Timeline> Timelines { get { return timelines; } set { timelines = value; } } public float Duration { get { return duration; } set { duration = value; } } public Animation (String name, ExposedList<Timeline> timelines, float duration) { if (name == null) throw new ArgumentNullException("name cannot be null."); if (timelines == null) throw new ArgumentNullException("timelines cannot be null."); this.name = name; this.timelines = timelines; this.duration = duration; } /// <summary>Poses the skeleton at the specified time for this animation.</summary> /// <param name="lastTime">The last time the animation was applied.</param> /// <param name="events">Any triggered events are added.</param> public void Apply (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events) { if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); if (loop && duration != 0) { time %= duration; lastTime %= duration; } ExposedList<Timeline> timelines = this.timelines; for (int i = 0, n = timelines.Count; i < n; i++) timelines.Items[i].Apply(skeleton, lastTime, time, events, 1); } /// <summary>Poses the skeleton at the specified time for this animation mixed with the current pose.</summary> /// <param name="lastTime">The last time the animation was applied.</param> /// <param name="events">Any triggered events are added.</param> /// <param name="alpha">The amount of this animation that affects the current pose.</param> public void Mix (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events, float alpha) { if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); if (loop && duration != 0) { time %= duration; lastTime %= duration; } ExposedList<Timeline> timelines = this.timelines; for (int i = 0, n = timelines.Count; i < n; i++) timelines.Items[i].Apply(skeleton, lastTime, time, events, alpha); } /// <param name="target">After the first and before the last entry.</param> internal static int binarySearch (float[] values, float target, int step) { int low = 0; int high = values.Length / step - 2; if (high == 0) return step; int current = (int)((uint)high >> 1); while (true) { if (values[(current + 1) * step] <= target) low = current + 1; else high = current; if (low == high) return (low + 1) * step; current = (int)((uint)(low + high) >> 1); } } /// <param name="target">After the first and before the last entry.</param> internal static int binarySearch (float[] values, float target) { int low = 0; int high = values.Length - 2; if (high == 0) return 1; int current = (int)((uint)high >> 1); while (true) { if (values[(current + 1)] <= target) low = current + 1; else high = current; if (low == high) return (low + 1); current = (int)((uint)(low + high) >> 1); } } internal static int linearSearch (float[] values, float target, int step) { for (int i = 0, last = values.Length - step; i <= last; i += step) if (values[i] > target) return i; return -1; } } public interface Timeline { /// <summary>Sets the value(s) for the specified time.</summary> /// <param name="events">May be null to not collect fired events.</param> void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha); } /// <summary>Base class for frames that use an interpolation bezier curve.</summary> abstract public class CurveTimeline : Timeline { protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2; protected const int BEZIER_SEGMENTS = 10, BEZIER_SIZE = BEZIER_SEGMENTS * 2 - 1; private float[] curves; // type, x, y, ... public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } } public CurveTimeline (int frameCount) { curves = new float[(frameCount - 1) * BEZIER_SIZE]; } abstract public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha); public void SetLinear (int frameIndex) { curves[frameIndex * BEZIER_SIZE] = LINEAR; } public void SetStepped (int frameIndex) { curves[frameIndex * BEZIER_SIZE] = STEPPED; } /// <summary>Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. /// cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of /// the difference between the keyframe's values.</summary> public void SetCurve (int frameIndex, float cx1, float cy1, float cx2, float cy2) { float subdiv1 = 1f / BEZIER_SEGMENTS, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; float pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; float tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; float dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3; float ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5; float dddfx = tmp2x * pre5, dddfy = tmp2y * pre5; int i = frameIndex * BEZIER_SIZE; float[] curves = this.curves; curves[i++] = BEZIER; float x = dfx, y = dfy; for (int n = i + BEZIER_SIZE - 1; i < n; i += 2) { curves[i] = x; curves[i + 1] = y; dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; x += dfx; y += dfy; } } public float GetCurvePercent (int frameIndex, float percent) { float[] curves = this.curves; int i = frameIndex * BEZIER_SIZE; float type = curves[i]; if (type == LINEAR) return percent; if (type == STEPPED) return 0; i++; float x = 0; for (int start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) { x = curves[i]; if (x >= percent) { float prevX, prevY; if (i == start) { prevX = 0; prevY = 0; } else { prevX = curves[i - 2]; prevY = curves[i - 1]; } return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); } } float y = curves[i - 1]; return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. } public float GetCurveType (int frameIndex) { return curves[frameIndex * BEZIER_SIZE]; } } public class RotateTimeline : CurveTimeline { protected const int PREV_FRAME_TIME = -2; protected const int FRAME_VALUE = 1; internal int boneIndex; internal float[] frames; public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, value, ... public RotateTimeline (int frameCount) : base(frameCount) { frames = new float[frameCount << 1]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, float angle) { frameIndex *= 2; frames[frameIndex] = time; frames[frameIndex + 1] = angle; } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. Bone bone = skeleton.bones.Items[boneIndex]; float amount; if (time >= frames[frames.Length - 2]) { // Time is after last frame. amount = bone.data.rotation + frames[frames.Length - 1] - bone.rotation; while (amount > 180) amount -= 360; while (amount < -180) amount += 360; bone.rotation += amount * alpha; return; } // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time, 2); float prevFrameValue = frames[frameIndex - 1]; float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime); percent = GetCurvePercent((frameIndex >> 1) - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); amount = frames[frameIndex + FRAME_VALUE] - prevFrameValue; while (amount > 180) amount -= 360; while (amount < -180) amount += 360; amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation; while (amount > 180) amount -= 360; while (amount < -180) amount += 360; bone.rotation += amount * alpha; } } public class TranslateTimeline : CurveTimeline { protected const int PREV_FRAME_TIME = -3; protected const int FRAME_X = 1; protected const int FRAME_Y = 2; internal int boneIndex; internal float[] frames; public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, value, value, ... public TranslateTimeline (int frameCount) : base(frameCount) { frames = new float[frameCount * 3]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, float x, float y) { frameIndex *= 3; frames[frameIndex] = time; frames[frameIndex + 1] = x; frames[frameIndex + 2] = y; } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. Bone bone = skeleton.bones.Items[boneIndex]; if (time >= frames[frames.Length - 3]) { // Time is after last frame. bone.x += (bone.data.x + frames[frames.Length - 2] - bone.x) * alpha; bone.y += (bone.data.y + frames[frames.Length - 1] - bone.y) * alpha; return; } // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time, 3); float prevFrameX = frames[frameIndex - 2]; float prevFrameY = frames[frameIndex - 1]; float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime); percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + FRAME_X] - prevFrameX) * percent - bone.x) * alpha; bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + FRAME_Y] - prevFrameY) * percent - bone.y) * alpha; } } public class ScaleTimeline : TranslateTimeline { public ScaleTimeline (int frameCount) : base(frameCount) { } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. Bone bone = skeleton.bones.Items[boneIndex]; if (time >= frames[frames.Length - 3]) { // Time is after last frame. bone.scaleX += (bone.data.scaleX * frames[frames.Length - 2] - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY * frames[frames.Length - 1] - bone.scaleY) * alpha; return; } // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time, 3); float prevFrameX = frames[frameIndex - 2]; float prevFrameY = frames[frameIndex - 1]; float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime); percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + FRAME_X] - prevFrameX) * percent) - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + FRAME_Y] - prevFrameY) * percent) - bone.scaleY) * alpha; } } public class ColorTimeline : CurveTimeline { protected const int PREV_FRAME_TIME = -5; protected const int FRAME_R = 1; protected const int FRAME_G = 2; protected const int FRAME_B = 3; protected const int FRAME_A = 4; internal int slotIndex; internal float[] frames; public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, r, g, b, a, ... public ColorTimeline (int frameCount) : base(frameCount) { frames = new float[frameCount * 5]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, float r, float g, float b, float a) { frameIndex *= 5; frames[frameIndex] = time; frames[frameIndex + 1] = r; frames[frameIndex + 2] = g; frames[frameIndex + 3] = b; frames[frameIndex + 4] = a; } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. float r, g, b, a; if (time >= frames[frames.Length - 5]) { // Time is after last frame. int i = frames.Length - 1; r = frames[i - 3]; g = frames[i - 2]; b = frames[i - 1]; a = frames[i]; } else { // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time, 5); float prevFrameR = frames[frameIndex - 4]; float prevFrameG = frames[frameIndex - 3]; float prevFrameB = frames[frameIndex - 2]; float prevFrameA = frames[frameIndex - 1]; float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime); percent = GetCurvePercent(frameIndex / 5 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); r = prevFrameR + (frames[frameIndex + FRAME_R] - prevFrameR) * percent; g = prevFrameG + (frames[frameIndex + FRAME_G] - prevFrameG) * percent; b = prevFrameB + (frames[frameIndex + FRAME_B] - prevFrameB) * percent; a = prevFrameA + (frames[frameIndex + FRAME_A] - prevFrameA) * percent; } Slot slot = skeleton.slots.Items[slotIndex]; if (alpha < 1) { slot.r += (r - slot.r) * alpha; slot.g += (g - slot.g) * alpha; slot.b += (b - slot.b) * alpha; slot.a += (a - slot.a) * alpha; } else { slot.r = r; slot.g = g; slot.b = b; slot.a = a; } } } public class AttachmentTimeline : Timeline { internal int slotIndex; internal float[] frames; private String[] attachmentNames; public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, ... public String[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } } public int FrameCount { get { return frames.Length; } } public AttachmentTimeline (int frameCount) { frames = new float[frameCount]; attachmentNames = new String[frameCount]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, String attachmentName) { frames[frameIndex] = time; attachmentNames[frameIndex] = attachmentName; } public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) { if (lastTime > time) Apply(skeleton, lastTime, int.MaxValue, null, 0); return; } else if (lastTime > time) // lastTime = -1; int frameIndex = (time >= frames[frames.Length - 1] ? frames.Length : Animation.binarySearch(frames, time)) - 1; if (frames[frameIndex] < lastTime) return; String attachmentName = attachmentNames[frameIndex]; skeleton.slots.Items[slotIndex].Attachment = attachmentName == null ? null : skeleton.GetAttachment(slotIndex, attachmentName); } } public class EventTimeline : Timeline { internal float[] frames; private Event[] events; public float[] Frames { get { return frames; } set { frames = value; } } // time, ... public Event[] Events { get { return events; } set { events = value; } } public int FrameCount { get { return frames.Length; } } public EventTimeline (int frameCount) { frames = new float[frameCount]; events = new Event[frameCount]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, Event e) { frames[frameIndex] = time; events[frameIndex] = e; } /// <summary>Fires events for frames > lastTime and <= time.</summary> public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { if (firedEvents == null) return; float[] frames = this.frames; int frameCount = frames.Length; if (lastTime > time) { // Fire events after last time for looped animations. Apply(skeleton, lastTime, int.MaxValue, firedEvents, alpha); lastTime = -1f; } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. return; if (time < frames[0]) return; // Time is before first frame. int frameIndex; if (lastTime < frames[0]) frameIndex = 0; else { frameIndex = Animation.binarySearch(frames, lastTime); float frame = frames[frameIndex]; while (frameIndex > 0) { // Fire multiple events with the same frame. if (frames[frameIndex - 1] != frame) break; frameIndex--; } } for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++) firedEvents.Add(events[frameIndex]); } } public class DrawOrderTimeline : Timeline { internal float[] frames; private int[][] drawOrders; public float[] Frames { get { return frames; } set { frames = value; } } // time, ... public int[][] DrawOrders { get { return drawOrders; } set { drawOrders = value; } } public int FrameCount { get { return frames.Length; } } public DrawOrderTimeline (int frameCount) { frames = new float[frameCount]; drawOrders = new int[frameCount][]; } /// <summary>Sets the time and value of the specified keyframe.</summary> /// <param name="drawOrder">May be null to use bind pose draw order.</param> public void SetFrame (int frameIndex, float time, int[] drawOrder) { frames[frameIndex] = time; drawOrders[frameIndex] = drawOrder; } public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. int frameIndex; if (time >= frames[frames.Length - 1]) // Time is after last frame. frameIndex = frames.Length - 1; else frameIndex = Animation.binarySearch(frames, time) - 1; ExposedList<Slot> drawOrder = skeleton.drawOrder; ExposedList<Slot> slots = skeleton.slots; int[] drawOrderToSetupIndex = drawOrders[frameIndex]; if (drawOrderToSetupIndex == null) { drawOrder.Clear(); for (int i = 0, n = slots.Count; i < n; i++) drawOrder.Add(slots.Items[i]); } else { for (int i = 0, n = drawOrderToSetupIndex.Length; i < n; i++) drawOrder.Items[i] = slots.Items[drawOrderToSetupIndex[i]]; } } } public class FFDTimeline : CurveTimeline { internal int slotIndex; internal float[] frames; private float[][] frameVertices; internal Attachment attachment; public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, ... public float[][] Vertices { get { return frameVertices; } set { frameVertices = value; } } public Attachment Attachment { get { return attachment; } set { attachment = value; } } public FFDTimeline (int frameCount) : base(frameCount) { frames = new float[frameCount]; frameVertices = new float[frameCount][]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, float[] vertices) { frames[frameIndex] = time; frameVertices[frameIndex] = vertices; } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { Slot slot = skeleton.slots.Items[slotIndex]; if (slot.attachment != attachment) return; float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. float[][] frameVertices = this.frameVertices; int vertexCount = frameVertices[0].Length; float[] vertices = slot.attachmentVertices; if (vertices.Length < vertexCount) { vertices = new float[vertexCount]; slot.attachmentVertices = vertices; } if (vertices.Length != vertexCount) alpha = 1; // Don't mix from uninitialized slot vertices. slot.attachmentVerticesCount = vertexCount; if (time >= frames[frames.Length - 1]) { // Time is after last frame. float[] lastVertices = frameVertices[frames.Length - 1]; if (alpha < 1) { for (int i = 0; i < vertexCount; i++) { float vertex = vertices[i]; vertices[i] = vertex + (lastVertices[i] - vertex) * alpha; } } else Array.Copy(lastVertices, 0, vertices, 0, vertexCount); return; } // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time); float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime); percent = GetCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); float[] prevVertices = frameVertices[frameIndex - 1]; float[] nextVertices = frameVertices[frameIndex]; if (alpha < 1) { for (int i = 0; i < vertexCount; i++) { float prev = prevVertices[i]; float vertex = vertices[i]; vertices[i] = vertex + (prev + (nextVertices[i] - prev) * percent - vertex) * alpha; } } else { for (int i = 0; i < vertexCount; i++) { float prev = prevVertices[i]; vertices[i] = prev + (nextVertices[i] - prev) * percent; } } } } public class IkConstraintTimeline : CurveTimeline { private const int PREV_FRAME_TIME = -3; private const int PREV_FRAME_MIX = -2; private const int PREV_FRAME_BEND_DIRECTION = -1; private const int FRAME_MIX = 1; internal int ikConstraintIndex; internal float[] frames; public int IkConstraintIndex { get { return ikConstraintIndex; } set { ikConstraintIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, mix, bendDirection, ... public IkConstraintTimeline (int frameCount) : base(frameCount) { frames = new float[frameCount * 3]; } /** Sets the time, mix and bend direction of the specified keyframe. */ public void SetFrame (int frameIndex, float time, float mix, int bendDirection) { frameIndex *= 3; frames[frameIndex] = time; frames[frameIndex + 1] = mix; frames[frameIndex + 2] = bendDirection; } override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) return; // Time is before first frame. IkConstraint ikConstraint = skeleton.ikConstraints.Items[ikConstraintIndex]; if (time >= frames[frames.Length - 3]) { // Time is after last frame. ikConstraint.mix += (frames[frames.Length - 2] - ikConstraint.mix) * alpha; ikConstraint.bendDirection = (int)frames[frames.Length - 1]; return; } // Interpolate between the previous frame and the current frame. int frameIndex = Animation.binarySearch(frames, time, 3); float prevFrameMix = frames[frameIndex + PREV_FRAME_MIX]; float frameTime = frames[frameIndex]; float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime); percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); float mix = prevFrameMix + (frames[frameIndex + FRAME_MIX] - prevFrameMix) * percent; ikConstraint.mix += (mix - ikConstraint.mix) * alpha; ikConstraint.bendDirection = (int)frames[frameIndex + PREV_FRAME_BEND_DIRECTION]; } } public class FlipXTimeline : Timeline { internal int boneIndex; internal float[] frames; public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, flip, ... public int FrameCount { get { return frames.Length >> 1; } } public FlipXTimeline (int frameCount) { frames = new float[frameCount << 1]; } /// <summary>Sets the time and value of the specified keyframe.</summary> public void SetFrame (int frameIndex, float time, bool flip) { frameIndex *= 2; frames[frameIndex] = time; frames[frameIndex + 1] = flip ? 1 : 0; } public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) { float[] frames = this.frames; if (time < frames[0]) { if (lastTime > time) Apply(skeleton, lastTime, int.MaxValue, null, 0); return; } else if (lastTime > time) // lastTime = -1; int frameIndex = (time >= frames[frames.Length - 2] ? frames.Length : Animation.binarySearch(frames, time, 2)) - 2; if (frames[frameIndex] < lastTime) return; SetFlip(skeleton.bones.Items[boneIndex], frames[frameIndex + 1] != 0); } virtual protected void SetFlip (Bone bone, bool flip) { bone.flipX = flip; } } public class FlipYTimeline : FlipXTimeline { public FlipYTimeline (int frameCount) : base(frameCount) { } override protected void SetFlip (Bone bone, bool flip) { bone.flipY = flip; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Threading.Tasks { public static class __TaskFactory { public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action> action) { return Observable.Zip(TaskFactoryValue, action, (TaskFactoryValueLambda, actionLambda) => TaskFactoryValueLambda.StartNew(actionLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action> action, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, action, cancellationToken, (TaskFactoryValueLambda, actionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.StartNew(actionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action> action, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, action, creationOptions, (TaskFactoryValueLambda, actionLambda, creationOptionsLambda) => TaskFactoryValueLambda.StartNew(actionLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action> action, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, action, cancellationToken, creationOptions, scheduler, (TaskFactoryValueLambda, actionLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.StartNew(actionLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action<System.Object>> action, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, action, state, (TaskFactoryValueLambda, actionLambda, stateLambda) => TaskFactoryValueLambda.StartNew(actionLambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action<System.Object>> action, IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, action, state, cancellationToken, (TaskFactoryValueLambda, actionLambda, stateLambda, cancellationTokenLambda) => TaskFactoryValueLambda.StartNew(actionLambda, stateLambda, cancellationTokenLambda) .ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action<System.Object>> action, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, action, state, creationOptions, (TaskFactoryValueLambda, actionLambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.StartNew(actionLambda, stateLambda, creationOptionsLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> StartNew( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Action<System.Object>> action, IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, action, state, cancellationToken, creationOptions, scheduler, (TaskFactoryValueLambda, actionLambda, stateLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.StartNew(actionLambda, stateLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TResult>> function) { return Observable.Zip(TaskFactoryValue, function, (TaskFactoryValueLambda, functionLambda) => TaskFactoryValueLambda.StartNew(functionLambda).ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TResult>> function, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, function, cancellationToken, (TaskFactoryValueLambda, functionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.StartNew(functionLambda, cancellationTokenLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TResult>> function, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, function, creationOptions, (TaskFactoryValueLambda, functionLambda, creationOptionsLambda) => TaskFactoryValueLambda.StartNew(functionLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TResult>> function, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, function, cancellationToken, creationOptions, scheduler, (TaskFactoryValueLambda, functionLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.StartNew(functionLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<System.Object, TResult>> function, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, function, state, (TaskFactoryValueLambda, functionLambda, stateLambda) => TaskFactoryValueLambda.StartNew(functionLambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<System.Object, TResult>> function, IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, function, state, cancellationToken, (TaskFactoryValueLambda, functionLambda, stateLambda, cancellationTokenLambda) => TaskFactoryValueLambda.StartNew(functionLambda, stateLambda, cancellationTokenLambda) .ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<System.Object, TResult>> function, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, function, state, creationOptions, (TaskFactoryValueLambda, functionLambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.StartNew(functionLambda, stateLambda, creationOptionsLambda) .ToObservable()).Flatten(); } public static IObservable<TResult> StartNew<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<System.Object, TResult>> function, IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, function, state, cancellationToken, creationOptions, scheduler, (TaskFactoryValueLambda, functionLambda, stateLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.StartNew(functionLambda, stateLambda, cancellationTokenLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<System.Action<System.IAsyncResult>> endMethod) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, creationOptions, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda, creationOptionsLambda) .ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, creationOptions, scheduler, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Func<System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, stateLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Func<System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda) .ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1, TArg2>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1, TArg2>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1, TArg2, TArg3>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, TArg3, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<TArg3> arg3, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, arg3, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> FromAsync<TArg1, TArg2, TArg3>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, TArg3, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<System.Action<System.IAsyncResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<TArg3> arg3, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<Func<System.IAsyncResult, TResult>> endMethod) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, creationOptions, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda, creationOptionsLambda) .ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.IAsyncResult> asyncResult, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, asyncResult, endMethod, creationOptions, scheduler, (TaskFactoryValueLambda, asyncResultLambda, endMethodLambda, creationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.FromAsync(asyncResultLambda, endMethodLambda, creationOptionsLambda, schedulerLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Func<System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, stateLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> FromAsync<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Func<System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda) .ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TArg2, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TArg2, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, TArg3, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<TArg3> arg3, IObservable<System.Object> state) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, arg3, state, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda).ToObservable()).Flatten(); } public static IObservable<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Func<TArg1, TArg2, TArg3, System.AsyncCallback, System.Object, System.IAsyncResult>> beginMethod, IObservable<Func<System.IAsyncResult, TResult>> endMethod, IObservable<TArg1> arg1, IObservable<TArg2> arg2, IObservable<TArg3> arg3, IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskCreationOptions> creationOptions) { return Observable.Zip(TaskFactoryValue, beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions, (TaskFactoryValueLambda, beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda, creationOptionsLambda) => TaskFactoryValueLambda.FromAsync(beginMethodLambda, endMethodLambda, arg1Lambda, arg2Lambda, arg3Lambda, stateLambda, creationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task[]>> continuationAction) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task[]>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task[]>> continuationAction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task[]>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>[]>> continuationAction) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>[]>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>[]>> continuationAction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAll<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>[]>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAll<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task[], TResult>> continuationFunction) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAll<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task[], TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAll<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task[], TResult>> continuationFunction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAll<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task[], TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAll<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>[], TResult>> continuationFunction) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAll<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>[], TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAll<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>[], TResult>> continuationFunction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAll<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>[], TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAll(tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task>> continuationAction) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task>> continuationAction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<System.Action<System.Threading.Tasks.Task>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAny<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task, TResult>> continuationFunction) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAny<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task, TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAny<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task, TResult>> continuationFunction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAny<TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<System.Threading.Tasks.Task[]> tasks, IObservable<Func<System.Threading.Tasks.Task, TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAny<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>, TResult>> continuationFunction) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda).ToObservable()) .Flatten(); } public static IObservable<TResult> ContinueWhenAny<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>, TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAny<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>, TResult>> continuationFunction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<TResult> ContinueWhenAny<TAntecedentResult, TResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Func<Task<TAntecedentResult>, TResult>> continuationFunction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationFunction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>>> continuationAction) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, cancellationTokenLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>>> continuationAction, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, continuationOptions, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, continuationOptionsLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, continuationOptionsLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> ContinueWhenAny<TAntecedentResult>( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue, IObservable<Task<TAntecedentResult>[]> tasks, IObservable<Action<Task<TAntecedentResult>>> continuationAction, IObservable<System.Threading.CancellationToken> cancellationToken, IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions, IObservable<System.Threading.Tasks.TaskScheduler> scheduler) { return Observable.Zip(TaskFactoryValue, tasks, continuationAction, cancellationToken, continuationOptions, scheduler, (TaskFactoryValueLambda, tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda) => TaskFactoryValueLambda.ContinueWhenAny(tasksLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda, schedulerLambda).ToObservable()) .Flatten(); } public static IObservable<System.Threading.CancellationToken> get_CancellationToken( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue) { return Observable.Select(TaskFactoryValue, (TaskFactoryValueLambda) => TaskFactoryValueLambda.CancellationToken); } public static IObservable<System.Threading.Tasks.TaskScheduler> get_Scheduler( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue) { return Observable.Select(TaskFactoryValue, (TaskFactoryValueLambda) => TaskFactoryValueLambda.Scheduler); } public static IObservable<System.Threading.Tasks.TaskCreationOptions> get_CreationOptions( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue) { return Observable.Select(TaskFactoryValue, (TaskFactoryValueLambda) => TaskFactoryValueLambda.CreationOptions); } public static IObservable<System.Threading.Tasks.TaskContinuationOptions> get_ContinuationOptions( this IObservable<System.Threading.Tasks.TaskFactory> TaskFactoryValue) { return Observable.Select(TaskFactoryValue, (TaskFactoryValueLambda) => TaskFactoryValueLambda.ContinuationOptions); } } }
using System; using Spring.Expressions.Parser.antlr.collections.impl; using Spring.Expressions.Parser.antlr.debug; using Stream = System.IO.Stream; using TextReader = System.IO.TextReader; using StringBuilder = System.Text.StringBuilder; using Hashtable = System.Collections.Hashtable; using Assembly = System.Reflection.Assembly; using EventHandlerList = System.ComponentModel.EventHandlerList; using BitSet = Spring.Expressions.Parser.antlr.collections.impl.BitSet; namespace Spring.Expressions.Parser.antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // public abstract class CharScanner : TokenStream, ICharScannerDebugSubject { internal const char NO_CHAR = (char) (0); public static readonly char EOF_CHAR = Char.MaxValue; // Used to store event delegates private EventHandlerList events_ = new EventHandlerList(); protected internal EventHandlerList Events { get { return events_; } } // The unique keys for each event that CharScanner [objects] can generate internal static readonly object EnterRuleEventKey = new object(); internal static readonly object ExitRuleEventKey = new object(); internal static readonly object DoneEventKey = new object(); internal static readonly object ReportErrorEventKey = new object(); internal static readonly object ReportWarningEventKey = new object(); internal static readonly object NewLineEventKey = new object(); internal static readonly object MatchEventKey = new object(); internal static readonly object MatchNotEventKey = new object(); internal static readonly object MisMatchEventKey = new object(); internal static readonly object MisMatchNotEventKey = new object(); internal static readonly object ConsumeEventKey = new object(); internal static readonly object LAEventKey = new object(); internal static readonly object SemPredEvaluatedEventKey = new object(); internal static readonly object SynPredStartedEventKey = new object(); internal static readonly object SynPredFailedEventKey = new object(); internal static readonly object SynPredSucceededEventKey = new object(); protected internal StringBuilder text; // text of current token protected bool saveConsumedInput = true; // does consume() save characters? /// <summary>Used for creating Token instances.</summary> protected TokenCreator tokenCreator; /// <summary>Used for caching lookahead characters.</summary> protected char cached_LA1; protected char cached_LA2; protected bool caseSensitive = true; protected bool caseSensitiveLiterals = true; protected Hashtable literals; // set by subclass /*Tab chars are handled by tab() according to this value; override * method to do anything weird with tabs. */ protected internal int tabsize = 8; protected internal IToken returnToken_ = null; // used to return tokens w/o using return val. protected internal LexerSharedInputState inputState; /*Used during filter mode to indicate that path is desired. * A subsequent scan error will report an error as usual if * acceptPath=true; */ protected internal bool commitToPath = false; /*Used to keep track of indentdepth for traceIn/Out */ protected internal int traceDepth = 0; public CharScanner() { text = new StringBuilder(); setTokenCreator(new CommonToken.CommonTokenCreator()); } public CharScanner(InputBuffer cb) : this() { inputState = new LexerSharedInputState(cb); cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } public CharScanner(LexerSharedInputState sharedState) : this() { inputState = sharedState; if (inputState != null) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } } public event TraceEventHandler EnterRule { add { Events.AddHandler(EnterRuleEventKey, value); } remove { Events.RemoveHandler(EnterRuleEventKey, value); } } public event TraceEventHandler ExitRule { add { Events.AddHandler(ExitRuleEventKey, value); } remove { Events.RemoveHandler(ExitRuleEventKey, value); } } public event TraceEventHandler Done { add { Events.AddHandler(DoneEventKey, value); } remove { Events.RemoveHandler(DoneEventKey, value); } } public event MessageEventHandler ErrorReported { add { Events.AddHandler(ReportErrorEventKey, value); } remove { Events.RemoveHandler(ReportErrorEventKey, value); } } public event MessageEventHandler WarningReported { add { Events.AddHandler(ReportWarningEventKey, value); } remove { Events.RemoveHandler(ReportWarningEventKey, value); } } public event NewLineEventHandler HitNewLine { add { Events.AddHandler(NewLineEventKey, value); } remove { Events.RemoveHandler(NewLineEventKey, value); } } public event MatchEventHandler MatchedChar { add { Events.AddHandler(MatchEventKey, value); } remove { Events.RemoveHandler(MatchEventKey, value); } } public event MatchEventHandler MatchedNotChar { add { Events.AddHandler(MatchNotEventKey, value); } remove { Events.RemoveHandler(MatchNotEventKey, value); } } public event MatchEventHandler MisMatchedChar { add { Events.AddHandler(MisMatchEventKey, value); } remove { Events.RemoveHandler(MisMatchEventKey, value); } } public event MatchEventHandler MisMatchedNotChar { add { Events.AddHandler(MisMatchNotEventKey, value); } remove { Events.RemoveHandler(MisMatchNotEventKey, value); } } public event TokenEventHandler ConsumedChar { add { Events.AddHandler(ConsumeEventKey, value); } remove { Events.RemoveHandler(ConsumeEventKey, value); } } public event TokenEventHandler CharLA { add { Events.AddHandler(LAEventKey, value); } remove { Events.RemoveHandler(LAEventKey, value); } } public event SemanticPredicateEventHandler SemPredEvaluated { add { Events.AddHandler(SemPredEvaluatedEventKey, value); } remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredStarted { add { Events.AddHandler(SynPredStartedEventKey, value); } remove { Events.RemoveHandler(SynPredStartedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredFailed { add { Events.AddHandler(SynPredFailedEventKey, value); } remove { Events.RemoveHandler(SynPredFailedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredSucceeded { add { Events.AddHandler(SynPredSucceededEventKey, value); } remove { Events.RemoveHandler(SynPredSucceededEventKey, value); } } // From interface TokenStream public virtual IToken nextToken() { return null; } public virtual void append(char c) { if (saveConsumedInput) { text.Append(c); } } public virtual void append(string s) { if (saveConsumedInput) { text.Append(s); } } public virtual void commit() { inputState.input.commit(); } public virtual void recover(RecognitionException ex, BitSet tokenSet) { consume(); consumeUntil(tokenSet); } public virtual void consume() { if (inputState.guessing == 0) { if (caseSensitive) { append(cached_LA1); } else { // use input.LA(), not LA(), to get original case // CharScanner.LA() would toLower it. append(inputState.input.LA(1)); } if (cached_LA1 == '\t') { tab(); } else { inputState.column++; } } if (caseSensitive) { cached_LA1 = inputState.input.consume(); cached_LA2 = inputState.input.LA(2); } else { cached_LA1 = toLower(inputState.input.consume()); cached_LA2 = toLower(inputState.input.LA(2)); } } /*Consume chars until one matches the given char */ public virtual void consumeUntil(int c) { while ((EOF_CHAR != cached_LA1) && (c != cached_LA1)) { consume(); } } /*Consume chars until one matches the given set */ public virtual void consumeUntil(BitSet bset) { while (cached_LA1 != EOF_CHAR && !bset.member(cached_LA1)) { consume(); } } public virtual bool getCaseSensitive() { return caseSensitive; } public bool getCaseSensitiveLiterals() { return caseSensitiveLiterals; } public virtual int getColumn() { return inputState.column; } public virtual void setColumn(int c) { inputState.column = c; } public virtual bool getCommitToPath() { return commitToPath; } public virtual string getFilename() { return inputState.filename; } public virtual InputBuffer getInputBuffer() { return inputState.input; } public virtual LexerSharedInputState getInputState() { return inputState; } public virtual void setInputState(LexerSharedInputState state) { inputState = state; } public virtual int getLine() { return inputState.line; } /*return a copy of the current text buffer */ public virtual string getText() { return text.ToString(); } public virtual IToken getTokenObject() { return returnToken_; } public virtual char LA(int i) { if (i == 1) { return cached_LA1; } if (i == 2) { return cached_LA2; } if (caseSensitive) { return inputState.input.LA(i); } else { return toLower(inputState.input.LA(i)); } } protected internal virtual IToken makeToken(int t) { IToken newToken = null; bool typeCreated; try { newToken = tokenCreator.Create(); if (newToken != null) { newToken.Type = t; newToken.setColumn(inputState.tokenStartColumn); newToken.setLine(inputState.tokenStartLine); // tracking real start line now: newToken.setLine(inputState.line); newToken.setFilename(inputState.filename); } typeCreated = true; } catch { typeCreated = false; } if (!typeCreated) { panic("Can't create Token object '" + tokenCreator.TokenTypeName + "'"); newToken = Token.badToken; } return newToken; } public virtual int mark() { return inputState.input.mark(); } public virtual void match(char c) { match((int) c); } public virtual void match(int c) { if (cached_LA1 != c) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this); } consume(); } public virtual void match(BitSet b) { if (!b.member(cached_LA1)) { throw new MismatchedCharException(cached_LA1, b, false, this); } consume(); } public virtual void match(string s) { int len = s.Length; for (int i = 0; i < len; i++) { if (cached_LA1 != s[i]) { throw new MismatchedCharException(cached_LA1, s[i], false, this); } consume(); } } public virtual void matchNot(char c) { matchNot((int) c); } public virtual void matchNot(int c) { if (cached_LA1 == c) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), true, this); } consume(); } public virtual void matchRange(int c1, int c2) { if (cached_LA1 < c1 || cached_LA1 > c2) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c1), Convert.ToChar(c2), false, this); } consume(); } public virtual void matchRange(char c1, char c2) { matchRange((int) c1, (int) c2); } public virtual void newline() { inputState.line++; inputState.column = 1; } /*advance the current column number by an appropriate amount * according to tab size. This method is called from consume(). */ public virtual void tab() { int c = getColumn(); int nc = (((c - 1) / tabsize) + 1) * tabsize + 1; // calculate tab stop setColumn(nc); } public virtual void setTabSize(int size) { tabsize = size; } public virtual int getTabSize() { return tabsize; } public virtual void panic() { //Console.Error.WriteLine("CharScanner: panic"); //Environment.Exit(1); panic(""); } /// <summary> /// This method is executed by ANTLR internally when it detected an illegal /// state that cannot be recovered from. /// The previous implementation of this method called <see cref="Environment.Exit"/> /// and writes directly to <see cref="Console.Error"/>, which is usually not /// appropriate when a translator is embedded into a larger application. /// </summary> /// <param name="s">Error message.</param> public virtual void panic(string s) { //Console.Error.WriteLine("CharScanner; panic: " + s); //Environment.Exit(1); throw new ANTLRPanicException("CharScanner::panic: " + s); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(RecognitionException ex) { Console.Error.WriteLine(ex); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(string s) { if (getFilename() == null) { Console.Error.WriteLine("error: " + s); } else { Console.Error.WriteLine(getFilename() + ": error: " + s); } } /*Parser warning-reporting function can be overridden in subclass */ public virtual void reportWarning(string s) { if (getFilename() == null) { Console.Error.WriteLine("warning: " + s); } else { Console.Error.WriteLine(getFilename() + ": warning: " + s); } } public virtual void refresh() { if (caseSensitive) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } else { cached_LA2 = toLower(inputState.input.LA(2)); cached_LA1 = toLower(inputState.input.LA(1)); } } public virtual void resetState(InputBuffer ib) { text.Length = 0; traceDepth = 0; inputState.resetInput(ib); refresh(); } public void resetState(Stream s) { resetState(new ByteBuffer(s)); } public void resetState(TextReader tr) { resetState(new CharBuffer(tr)); } public virtual void resetText() { text.Length = 0; inputState.tokenStartColumn = inputState.column; inputState.tokenStartLine = inputState.line; } public virtual void rewind(int pos) { inputState.input.rewind(pos); //setColumn(inputState.tokenStartColumn); if (caseSensitive) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } else { cached_LA2 = toLower(inputState.input.LA(2)); cached_LA1 = toLower(inputState.input.LA(1)); } } public virtual void setCaseSensitive(bool t) { caseSensitive = t; if (caseSensitive) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } else { cached_LA2 = toLower(inputState.input.LA(2)); cached_LA1 = toLower(inputState.input.LA(1)); } } public virtual void setCommitToPath(bool commit) { commitToPath = commit; } public virtual void setFilename(string f) { inputState.filename = f; } public virtual void setLine(int line) { inputState.line = line; } public virtual void setText(string s) { resetText(); text.Append(s); } public virtual void setTokenObjectClass(string cl) { this.tokenCreator = new ReflectionBasedTokenCreator(this, cl); } public virtual void setTokenCreator(TokenCreator tokenCreator) { this.tokenCreator = tokenCreator; } // Test the token text against the literals table // Override this method to perform a different literals test public virtual int testLiteralsTable(int ttype) { string tokenText = text.ToString(); if ( (tokenText == null) || (tokenText == string.Empty) ) return ttype; else { object typeAsObject = literals[tokenText]; return (typeAsObject == null) ? ttype : ((int) typeAsObject); } } /*Test the text passed in against the literals table * Override this method to perform a different literals test * This is used primarily when you want to test a portion of * a token. */ public virtual int testLiteralsTable(string someText, int ttype) { if ( (someText == null) || (someText == string.Empty) ) return ttype; else { object typeAsObject = literals[someText]; return (typeAsObject == null) ? ttype : ((int) typeAsObject); } } // Override this method to get more specific case handling public virtual char toLower(int c) { return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture); } public virtual void traceIndent() { for (int i = 0; i < traceDepth; i++) Console.Out.Write(" "); } public virtual void traceIn(string rname) { traceDepth += 1; traceIndent(); Console.Out.WriteLine("> lexer " + rname + "; c==" + LA(1)); } public virtual void traceOut(string rname) { traceIndent(); Console.Out.WriteLine("< lexer " + rname + "; c==" + LA(1)); traceDepth -= 1; } /*This method is called by YourLexer.nextToken() when the lexer has * hit EOF condition. EOF is NOT a character. * This method is not called if EOF is reached during * syntactic predicate evaluation or during evaluation * of normal lexical rules, which presumably would be * an IOException. This traps the "normal" EOF condition. * * uponEOF() is called after the complete evaluation of * the previous token and only if your parser asks * for another token beyond that last non-EOF token. * * You might want to throw token or char stream exceptions * like: "Heh, premature eof" or a retry stream exception * ("I found the end of this file, go back to referencing file"). */ public virtual void uponEOF() { } private class ReflectionBasedTokenCreator : TokenCreator { protected ReflectionBasedTokenCreator() {} public ReflectionBasedTokenCreator(CharScanner owner, string tokenTypeName) { this.owner = owner; SetTokenType(tokenTypeName); } private CharScanner owner; /// <summary> /// The fully qualified name of the Token type to create. /// </summary> private string tokenTypeName; /// <summary> /// Type object used as a template for creating tokens by reflection. /// </summary> private Type tokenTypeObject; /// <summary> /// Returns the fully qualified name of the Token type that this /// class creates. /// </summary> private void SetTokenType(string tokenTypeName) { this.tokenTypeName = tokenTypeName; foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies()) { try { tokenTypeObject = assem.GetType(tokenTypeName); if (tokenTypeObject != null) { break; } } catch { throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'"); } } if (tokenTypeObject==null) throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'"); } /// <summary> /// Returns the fully qualified name of the Token type that this /// class creates. /// </summary> public override string TokenTypeName { get { return tokenTypeName; } } /// <summary> /// Constructs a <see cref="Token"/> instance. /// </summary> public override IToken Create() { IToken newToken = null; try { newToken = (Token) Activator.CreateInstance(tokenTypeObject); } catch { // supress exception } return newToken; } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using System.IO; using MetroFramework.Drawing.Html.Adapters.Entities; using MetroFramework.Drawing.Html.Core; using MetroFramework.Drawing.Html.Core.Entities; using MetroFramework.Drawing.Html.Core.Handlers; using MetroFramework.Drawing.Html.Core.Utils; namespace MetroFramework.Drawing.Html.Adapters { /// <summary> /// Platform adapter to bridge platform specific objects to HTML Renderer core library.<br/> /// Core uses abstract renderer objects (RAdapter/RControl/REtc...) to access platform specific functionality, the concrete platforms /// implements those objects to provide concrete platform implementation. Those allowing the core library to be platform agnostic. /// <para> /// Platforms: WinForms, WPF, Metro, PDF renders, etc.<br/> /// Objects: UI elements(Controls), Graphics(Render context), Colors, Brushes, Pens, Fonts, Images, Clipboard, etc.<br/> /// </para> /// </summary> /// <remarks> /// It is best to have a singleton instance of this class for concrete implementation!<br/> /// This is because it holds caches of default CssData, Images, Fonts and Brushes. /// </remarks> public abstract class RAdapter { #region Fields/Consts /// <summary> /// cache of brush color to brush instance /// </summary> private readonly Dictionary<RColor, RBrush> _brushesCache = new Dictionary<RColor, RBrush>(); /// <summary> /// cache of pen color to pen instance /// </summary> private readonly Dictionary<RColor, RPen> _penCache = new Dictionary<RColor, RPen>(); /// <summary> /// cache of all the font used not to create same font again and again /// </summary> private readonly FontsHandler _fontsHandler; /// <summary> /// default CSS parsed data singleton /// </summary> private CssData _defaultCssData; /// <summary> /// image used to draw loading image icon /// </summary> private RImage _loadImage; /// <summary> /// image used to draw error image icon /// </summary> private RImage _errorImage; #endregion /// <summary> /// Init. /// </summary> protected RAdapter() { _fontsHandler = new FontsHandler(this); } /// <summary> /// Get the default CSS stylesheet data. /// </summary> public CssData DefaultCssData { get { return _defaultCssData ?? (_defaultCssData = CssData.Parse(this, CssDefaults.DefaultStyleSheet, false)); } } /// <summary> /// Resolve color value from given color name. /// </summary> /// <param name="colorName">the color name</param> /// <returns>color value</returns> public RColor GetColor(string colorName) { ArgChecker.AssertArgNotNullOrEmpty(colorName, "colorName"); return GetColorInt(colorName); } /// <summary> /// Get cached pen instance for the given color. /// </summary> /// <param name="color">the color to get pen for</param> /// <returns>pen instance</returns> public RPen GetPen(RColor color) { RPen pen; if (!_penCache.TryGetValue(color, out pen)) { _penCache[color] = pen = CreatePen(color); } return pen; } /// <summary> /// Get cached solid brush instance for the given color. /// </summary> /// <param name="color">the color to get brush for</param> /// <returns>brush instance</returns> public RBrush GetSolidBrush(RColor color) { RBrush brush; if (!_brushesCache.TryGetValue(color, out brush)) { _brushesCache[color] = brush = CreateSolidBrush(color); } return brush; } /// <summary> /// Get linear gradient color brush from <paramref name="color1"/> to <paramref name="color2"/>. /// </summary> /// <param name="rect">the rectangle to get the brush for</param> /// <param name="color1">the start color of the gradient</param> /// <param name="color2">the end color of the gradient</param> /// <param name="angle">the angle to move the gradient from start color to end color in the rectangle</param> /// <returns>linear gradient color brush instance</returns> public RBrush GetLinearGradientBrush(RRect rect, RColor color1, RColor color2, double angle) { return CreateLinearGradientBrush(rect, color1, color2, angle); } /// <summary> /// Convert image object returned from <see cref="HtmlImageLoadEventArgs"/> to <see cref="RImage"/>. /// </summary> /// <param name="image">the image returned from load event</param> /// <returns>converted image or null</returns> public RImage ConvertImage(object image) { // TODO:a remove this by creating better API. return ConvertImageInt(image); } /// <summary> /// Create an <see cref="RImage"/> object from the given stream. /// </summary> /// <param name="memoryStream">the stream to create image from</param> /// <returns>new image instance</returns> public RImage ImageFromStream(Stream memoryStream) { return ImageFromStreamInt(memoryStream); } /// <summary> /// Check if the given font exists in the system by font family name. /// </summary> /// <param name="font">the font name to check</param> /// <returns>true - font exists by given family name, false - otherwise</returns> public bool IsFontExists(string font) { return _fontsHandler.IsFontExists(font); } /// <summary> /// Adds a font family to be used. /// </summary> /// <param name="fontFamily">The font family to add.</param> public void AddFontFamily(RFontFamily fontFamily) { _fontsHandler.AddFontFamily(fontFamily); } /// <summary> /// Adds a font mapping from <paramref name="fromFamily"/> to <paramref name="toFamily"/> iff the <paramref name="fromFamily"/> is not found.<br/> /// When the <paramref name="fromFamily"/> font is used in rendered html and is not found in existing /// fonts (installed or added) it will be replaced by <paramref name="toFamily"/>.<br/> /// </summary> /// <param name="fromFamily">the font family to replace</param> /// <param name="toFamily">the font family to replace with</param> public void AddFontFamilyMapping(string fromFamily, string toFamily) { _fontsHandler.AddFontFamilyMapping(fromFamily, toFamily); } /// <summary> /// Get font instance by given font family name, size and style. /// </summary> /// <param name="family">the font family name</param> /// <param name="size">font size</param> /// <param name="style">font style</param> /// <returns>font instance</returns> public RFont GetFont(string family, double size, RFontStyle style) { return _fontsHandler.GetCachedFont(family, size, style); } /// <summary> /// Get image to be used while HTML image is loading. /// </summary> public RImage GetLoadingImage() { if (_loadImage == null) { var stream = typeof(HtmlRendererUtils).Assembly.GetManifestResourceStream("TheArtOfDev.HtmlRenderer.Core.Utils.ImageLoad.png"); if (stream != null) _loadImage = ImageFromStream(stream); } return _loadImage; } /// <summary> /// Get image to be used if HTML image load failed. /// </summary> public RImage GetLoadingFailedImage() { if (_errorImage == null) { var stream = typeof(HtmlRendererUtils).Assembly.GetManifestResourceStream("TheArtOfDev.HtmlRenderer.Core.Utils.ImageError.png"); if (stream != null) _errorImage = ImageFromStream(stream); } return _errorImage; } /// <summary> /// Get data object for the given html and plain text data.<br /> /// The data object can be used for clipboard or drag-drop operation.<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="html">the html data</param> /// <param name="plainText">the plain text data</param> /// <returns>drag-drop data object</returns> public object GetClipboardDataObject(string html, string plainText) { return GetClipboardDataObjectInt(html, plainText); } /// <summary> /// Set the given text to the clipboard<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="text">the text to set</param> public void SetToClipboard(string text) { SetToClipboardInt(text); } /// <summary> /// Set the given html and plain text data to clipboard.<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="html">the html data</param> /// <param name="plainText">the plain text data</param> public void SetToClipboard(string html, string plainText) { SetToClipboardInt(html, plainText); } /// <summary> /// Set the given image to clipboard.<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="image">the image object to set to clipboard</param> public void SetToClipboard(RImage image) { SetToClipboardInt(image); } /// <summary> /// Create a context menu that can be used on the control<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <returns>new context menu</returns> public RContextMenu GetContextMenu() { return CreateContextMenuInt(); } /// <summary> /// Save the given image to file by showing save dialog to the client.<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="image">the image to save</param> /// <param name="name">the name of the image for save dialog</param> /// <param name="extension">the extension of the image for save dialog</param> /// <param name="control">optional: the control to show the dialog on</param> public void SaveToFile(RImage image, string name, string extension, RControl control = null) { SaveToFileInt(image, name, extension, control); } /// <summary> /// Get font instance by given font family name, size and style. /// </summary> /// <param name="family">the font family name</param> /// <param name="size">font size</param> /// <param name="style">font style</param> /// <returns>font instance</returns> internal RFont CreateFont(string family, double size, RFontStyle style) { return CreateFontInt(family, size, style); } /// <summary> /// Get font instance by given font family instance, size and style.<br/> /// Used to support custom fonts that require explicit font family instance to be created. /// </summary> /// <param name="family">the font family instance</param> /// <param name="size">font size</param> /// <param name="style">font style</param> /// <returns>font instance</returns> internal RFont CreateFont(RFontFamily family, double size, RFontStyle style) { return CreateFontInt(family, size, style); } #region Private/Protected methods /// <summary> /// Resolve color value from given color name. /// </summary> /// <param name="colorName">the color name</param> /// <returns>color value</returns> protected abstract RColor GetColorInt(string colorName); /// <summary> /// Get cached pen instance for the given color. /// </summary> /// <param name="color">the color to get pen for</param> /// <returns>pen instance</returns> protected abstract RPen CreatePen(RColor color); /// <summary> /// Get cached solid brush instance for the given color. /// </summary> /// <param name="color">the color to get brush for</param> /// <returns>brush instance</returns> protected abstract RBrush CreateSolidBrush(RColor color); /// <summary> /// Get linear gradient color brush from <paramref name="color1"/> to <paramref name="color2"/>. /// </summary> /// <param name="rect">the rectangle to get the brush for</param> /// <param name="color1">the start color of the gradient</param> /// <param name="color2">the end color of the gradient</param> /// <param name="angle">the angle to move the gradient from start color to end color in the rectangle</param> /// <returns>linear gradient color brush instance</returns> protected abstract RBrush CreateLinearGradientBrush(RRect rect, RColor color1, RColor color2, double angle); /// <summary> /// Convert image object returned from <see cref="HtmlImageLoadEventArgs"/> to <see cref="RImage"/>. /// </summary> /// <param name="image">the image returned from load event</param> /// <returns>converted image or null</returns> protected abstract RImage ConvertImageInt(object image); /// <summary> /// Create an <see cref="RImage"/> object from the given stream. /// </summary> /// <param name="memoryStream">the stream to create image from</param> /// <returns>new image instance</returns> protected abstract RImage ImageFromStreamInt(Stream memoryStream); /// <summary> /// Get font instance by given font family name, size and style. /// </summary> /// <param name="family">the font family name</param> /// <param name="size">font size</param> /// <param name="style">font style</param> /// <returns>font instance</returns> protected abstract RFont CreateFontInt(string family, double size, RFontStyle style); /// <summary> /// Get font instance by given font family instance, size and style.<br/> /// Used to support custom fonts that require explicit font family instance to be created. /// </summary> /// <param name="family">the font family instance</param> /// <param name="size">font size</param> /// <param name="style">font style</param> /// <returns>font instance</returns> protected abstract RFont CreateFontInt(RFontFamily family, double size, RFontStyle style); /// <summary> /// Get data object for the given html and plain text data.<br /> /// The data object can be used for clipboard or drag-drop operation. /// </summary> /// <param name="html">the html data</param> /// <param name="plainText">the plain text data</param> /// <returns>drag-drop data object</returns> protected virtual object GetClipboardDataObjectInt(string html, string plainText) { throw new NotImplementedException(); } /// <summary> /// Set the given text to the clipboard /// </summary> /// <param name="text">the text to set</param> protected virtual void SetToClipboardInt(string text) { throw new NotImplementedException(); } /// <summary> /// Set the given html and plain text data to clipboard. /// </summary> /// <param name="html">the html data</param> /// <param name="plainText">the plain text data</param> protected virtual void SetToClipboardInt(string html, string plainText) { throw new NotImplementedException(); } /// <summary> /// Set the given image to clipboard. /// </summary> /// <param name="image"></param> protected virtual void SetToClipboardInt(RImage image) { throw new NotImplementedException(); } /// <summary> /// Create a context menu that can be used on the control /// </summary> /// <returns>new context menu</returns> protected virtual RContextMenu CreateContextMenuInt() { throw new NotImplementedException(); } /// <summary> /// Save the given image to file by showing save dialog to the client. /// </summary> /// <param name="image">the image to save</param> /// <param name="name">the name of the image for save dialog</param> /// <param name="extension">the extension of the image for save dialog</param> /// <param name="control">optional: the control to show the dialog on</param> protected virtual void SaveToFileInt(RImage image, string name, string extension, RControl control = null) { throw new NotImplementedException(); } #endregion } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions 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. */ #endregion using System; using System.IO; using System.Net; using System.Xml; using System.Text; using System.Drawing; using System.Threading; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Web.Services.Protocols; using System.Text.RegularExpressions; namespace MSNPSharp { using MSNPSharp.IO; using MSNPSharp.Core; using MSNPSharp.MSNWS.MSNABSharingService; using MSNPSharp.MSNWS.MSNDirectoryService; partial class ContactService { private void FindMembershipAsync(string partnerScenario, FindMembershipCompletedEventHandler findMembershipCallback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("FindMembership", new MSNPSharpException("You don't have access right on this action anymore."))); return; } bool msdeltasOnly = false; DateTime serviceLastChange = WebServiceDateTimeConverter.ConvertToDateTime(WebServiceConstants.ZeroTime); DateTime msLastChange = WebServiceDateTimeConverter.ConvertToDateTime(AddressBook.MembershipLastChange); string strLastChange = WebServiceConstants.ZeroTime; if (msLastChange != serviceLastChange) { msdeltasOnly = true; strLastChange = AddressBook.MembershipLastChange; } FindMembershipRequestType request = new FindMembershipRequestType(); request.view = "Full"; // NO default! request.deltasOnly = msdeltasOnly; request.lastChange = strLastChange; request.serviceFilter = new ServiceFilter(); request.serviceFilter.Types = new ServiceName[] { ServiceName.Messenger, ServiceName.IMAvailability, ServiceName.SocialNetwork }; MsnServiceState FindMembershipObject = new MsnServiceState(partnerScenario, "FindMembership", true); SharingServiceBinding sharingService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, FindMembershipObject); sharingService.FindMembershipCompleted += delegate(object sender, FindMembershipCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(sharingService, MsnServiceType.Sharing, e)); // Cancelled or signed off if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (e.Error != null) { // Handle errors and recall this method if necesarry. if (e.Error.Message.ToLowerInvariant().Contains("need to do full sync") || e.Error.Message.ToLowerInvariant().Contains("full sync required")) { // recursive Call ----------------------------- DeleteRecordFile(true); FindMembershipAsync(partnerScenario, findMembershipCallback); } else if (e.Error.Message.ToLowerInvariant().Contains("address book does not exist")) { ABAddRequestType abAddRequest = new ABAddRequestType(); abAddRequest.abInfo = new abInfoType(); abAddRequest.abInfo.ownerEmail = NSMessageHandler.Owner.Account; abAddRequest.abInfo.ownerPuid = 0; abAddRequest.abInfo.fDefault = true; MsnServiceState ABAddObject = new MsnServiceState(partnerScenario, "ABAdd", true); ABServiceBinding abservice = (ABServiceBinding)CreateService(MsnServiceType.AB, ABAddObject); abservice.ABAddCompleted += delegate(object srv, ABAddCompletedEventArgs abadd_e) { OnAfterCompleted(new ServiceOperationEventArgs(abservice, MsnServiceType.AB, abadd_e)); if (abadd_e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (abadd_e.Error == null) { // recursive Call ----------------------------- DeleteRecordFile(true); FindMembershipAsync(partnerScenario, findMembershipCallback); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abservice, MsnServiceType.AB, ABAddObject, abAddRequest)); } else { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "UNHANDLED ERROR: " + e.Error.Message.ToString(), GetType().Name); // Pass to the callback if (findMembershipCallback != null) { findMembershipCallback(sharingService, e); } } } else { // No error, fire event handler. if (findMembershipCallback != null) { findMembershipCallback(sharingService, e); } } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(sharingService, MsnServiceType.Sharing, FindMembershipObject, request)); } private void ABFindContactsPagedAsync(string partnerScenario, abHandleType abHandle, ABFindContactsPagedCompletedEventHandler abFindContactsPagedCallback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABFindContactsPaged", new MSNPSharpException("You don't have access right on this action anymore."))); return; } bool deltasOnly = false; ABFindContactsPagedRequestType request = new ABFindContactsPagedRequestType(); request.abView = "MessengerClient8"; //NO default! if (abHandle == null || abHandle.ABId == WebServiceConstants.MessengerIndividualAddressBookId) { request.extendedContent = "AB AllGroups CircleResult"; request.filterOptions = new filterOptionsType(); request.filterOptions.ContactFilter = new ContactFilterType(); if (DateTime.MinValue != WebServiceDateTimeConverter.ConvertToDateTime(AddressBook.GetAddressBookLastChange(WebServiceConstants.MessengerIndividualAddressBookId))) { deltasOnly = true; request.filterOptions.LastChanged = AddressBook.GetAddressBookLastChange(WebServiceConstants.MessengerIndividualAddressBookId); } request.filterOptions.DeltasOnly = deltasOnly; request.filterOptions.ContactFilter.IncludeHiddenContacts = true; // Without these two lines we cannot get the Connect contacts correctly. request.filterOptions.ContactFilter.IncludeShellContactsSpecified = true; request.filterOptions.ContactFilter.IncludeShellContacts = true; } else { request.extendedContent = "AB"; request.abHandle = abHandle; } MsnServiceState ABFindContactsPagedObject = new MsnServiceState(partnerScenario, "ABFindContactsPaged", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABFindContactsPagedObject); abService.ABFindContactsPagedCompleted += delegate(object sender, ABFindContactsPagedCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); // Cancelled or signed off if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (e.Error != null) { // Handle errors and recall this method if necesarry. if ((e.Error.Message.ToLowerInvariant().Contains("need to do full sync") || e.Error.Message.ToLowerInvariant().Contains("full sync required"))) { if (abHandle == null || abHandle.ABId == WebServiceConstants.MessengerIndividualAddressBookId) { // Default addressbook DeleteRecordFile(true); } else { // Circle addressbook AddressBook.RemoveCircle(new Guid(abHandle.ABId).ToString("D").ToLowerInvariant(), false); } // recursive Call ----------------------------- ABFindContactsPagedAsync(partnerScenario, abHandle, abFindContactsPagedCallback); } else { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "UNHANDLED ERROR: " + e.Error.Message.ToString(), GetType().Name); // Pass to the callback if (abFindContactsPagedCallback != null) { abFindContactsPagedCallback(sender, e); } } } else { // No error, fire event handler. if (abFindContactsPagedCallback != null) { abFindContactsPagedCallback(sender, e); } } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABFindContactsPagedObject, request)); } private void FindFriendsInCommonAsync(Guid abId, long cid, int count, FindFriendsInCommonCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("FindFriendsInCommon", new MSNPSharpException("You don't have access right on this action anymore."))); return; } if (cid == NSMessageHandler.Owner.CID) return; abHandleType abHandle = new abHandleType(); abHandle.Puid = 0; if (abId != Guid.Empty) { // Find in circle abHandle.ABId = abId.ToString("D").ToLowerInvariant(); } else if (cid != 0) { // Find by CID abHandle.Cid = cid; } FindFriendsInCommonRequestType request = new FindFriendsInCommonRequestType(); request.domainID = DomainIds.WindowsLiveDomain; request.maxResults = count; request.options = "List Count Matched Unmatched "; // IncludeInfo request.targetAB = abHandle; MsnServiceState findFriendsInCommonObject = new MsnServiceState(PartnerScenario.Timer, "FindFriendsInCommon", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, findFriendsInCommonObject); abService.FindFriendsInCommonCompleted += delegate(object service, FindFriendsInCommonCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, findFriendsInCommonObject, request)); } private void CreateContactAsync(string account, IMAddressInfoType network, Guid abId, CreateContactCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("CreateContact", new MSNPSharpException("You don't have access right on this action anymore."))); return; } CreateContactType request = new CreateContactType(); if (network == IMAddressInfoType.Telephone) { contactInfoType contactInfo = new contactInfoType(); contactPhoneType cpt = new contactPhoneType(); cpt.contactPhoneType1 = ContactPhoneTypes.ContactPhoneMobile; cpt.number = account; contactInfo.phones = new contactPhoneType[] { cpt }; request.contactInfo = contactInfo; } else { contactHandleType contactHandle = new contactHandleType(); contactHandle.Email = account; contactHandle.Cid = 0; contactHandle.Puid = 0; contactHandle.CircleId = WebServiceConstants.MessengerIndividualAddressBookId; request.contactHandle = contactHandle; } if (abId != Guid.Empty) { abHandleType abHandle = new abHandleType(); abHandle.ABId = abId.ToString("D").ToLowerInvariant(); abHandle.Puid = 0; abHandle.Cid = 0; request.abHandle = abHandle; } MsnServiceState createContactObject = new MsnServiceState(abId == Guid.Empty ? PartnerScenario.ContactSave : PartnerScenario.CircleSave, "CreateContact", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, createContactObject); abService.CreateContactCompleted += delegate(object service, CreateContactCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, createContactObject, request)); } private void DeleteContactAsync(Contact contact, DeleteContactCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("DeleteContact", new MSNPSharpException("You don't have access right on this action anymore."))); return; } DeleteContactRequestType request = new DeleteContactRequestType(); request.contactId = contact.Guid.ToString("D").ToLowerInvariant(); MsnServiceState deleteContactObject = new MsnServiceState(PartnerScenario.Timer, "DeleteContact", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, deleteContactObject); abService.DeleteContactCompleted += delegate(object service, DeleteContactCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, deleteContactObject, request)); } private void UpdateContactAsync(ContactType contact, string abId, ABContactUpdateCompletedEventHandler callback) { ABContactUpdateRequestType request = new ABContactUpdateRequestType(); request.abId = abId; request.contacts = new ContactType[] { contact }; request.options = new ABContactUpdateRequestTypeOptions(); request.options.EnableAllowListManagementSpecified = true; request.options.EnableAllowListManagement = true; MsnServiceState ABContactUpdateObject = new MsnServiceState(contact.contactInfo.isMessengerUser ? PartnerScenario.ContactSave : PartnerScenario.Timer, "ABContactUpdate", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABContactUpdateObject); abService.ABContactUpdateCompleted += delegate(object service, ABContactUpdateCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABContactUpdateObject, request)); } private void BreakConnectionAsync(Guid contactGuid, Guid abID, bool block, bool delete, BreakConnectionCompletedEventHandler callback) { BreakConnectionRequestType breakconnRequest = new BreakConnectionRequestType(); breakconnRequest.contactId = contactGuid.ToString("D"); breakconnRequest.blockContact = block; breakconnRequest.deleteContact = delete; if (abID != Guid.Empty) { abHandleType handler = new abHandleType(); handler.ABId = abID.ToString("D"); handler.Cid = 0; handler.Puid = 0; breakconnRequest.abHandle = handler; } MsnServiceState breakConnectionObject = new MsnServiceState(PartnerScenario.BlockUnblock, "BreakConnection", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, breakConnectionObject); abService.BreakConnectionCompleted += delegate(object sender, BreakConnectionCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(sender, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, breakConnectionObject, breakconnRequest)); } private void ManageWLConnectionAsync(Guid contactGuid, Guid abID, string inviteMessage, bool connection, bool presence, int action, int relType, int relRole, ManageWLConnectionCompletedEventHandler callback) { ManageWLConnectionRequestType wlconnectionRequest = new ManageWLConnectionRequestType(); wlconnectionRequest.contactId = contactGuid.ToString("D"); wlconnectionRequest.connection = connection; wlconnectionRequest.presence = presence; wlconnectionRequest.action = action; wlconnectionRequest.relationshipType = relType; wlconnectionRequest.relationshipRole = relRole; if (!String.IsNullOrEmpty(inviteMessage)) { Annotation anno = new Annotation(); anno.Name = AnnotationNames.MSN_IM_InviteMessage; anno.Value = inviteMessage; wlconnectionRequest.annotations = new Annotation[] { anno }; } if (abID != Guid.Empty) { abHandleType abHandle = new abHandleType(); abHandle.ABId = abID.ToString("D").ToLowerInvariant(); abHandle.Puid = 0; abHandle.Cid = 0; wlconnectionRequest.abHandle = abHandle; } MsnServiceState manageWLConnectionObject = new MsnServiceState(abID == Guid.Empty ? PartnerScenario.ContactSave : PartnerScenario.CircleInvite, "ManageWLConnection", true); ABServiceBinding abServiceBinding = (ABServiceBinding)CreateService(MsnServiceType.AB, manageWLConnectionObject); abServiceBinding.ManageWLConnectionCompleted += delegate(object wlcSender, ManageWLConnectionCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abServiceBinding, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(wlcSender, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abServiceBinding, MsnServiceType.AB, manageWLConnectionObject, wlconnectionRequest)); } private void ABGroupAddAsync(string groupName, ABGroupAddCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABGroupAdd", new MSNPSharpException("You don't have access right on this action anymore."))); return; } ABGroupAddRequestType request = new ABGroupAddRequestType(); request.abId = WebServiceConstants.MessengerIndividualAddressBookId; request.groupAddOptions = new ABGroupAddRequestTypeGroupAddOptions(); request.groupAddOptions.fRenameOnMsgrConflict = false; request.groupAddOptions.fRenameOnMsgrConflictSpecified = true; request.groupInfo = new ABGroupAddRequestTypeGroupInfo(); request.groupInfo.GroupInfo = new groupInfoType(); request.groupInfo.GroupInfo.name = groupName; request.groupInfo.GroupInfo.fMessenger = false; request.groupInfo.GroupInfo.fMessengerSpecified = true; request.groupInfo.GroupInfo.groupType = WebServiceConstants.MessengerGroupType; request.groupInfo.GroupInfo.annotations = new Annotation[] { new Annotation() }; request.groupInfo.GroupInfo.annotations[0].Name = AnnotationNames.MSN_IM_Display; request.groupInfo.GroupInfo.annotations[0].Value = "1"; MsnServiceState ABGroupAddObject = new MsnServiceState(PartnerScenario.GroupSave, "ABGroupAdd", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABGroupAddObject); abService.ABGroupAddCompleted += delegate(object service, ABGroupAddCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABGroupAddObject, request)); } private void ABGroupUpdateAsync(ContactGroup group, string newGroupName, ABGroupUpdateCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABGroupUpdate", new MSNPSharpException("You don't have access right on this action anymore."))); return; } ABGroupUpdateRequestType request = new ABGroupUpdateRequestType(); request.abId = WebServiceConstants.MessengerIndividualAddressBookId; request.groups = new GroupType[1] { new GroupType() }; request.groups[0].groupId = group.Guid; request.groups[0].propertiesChanged = PropertyString.GroupName; //"GroupName"; request.groups[0].groupInfo = new groupInfoType(); request.groups[0].groupInfo.name = newGroupName; MsnServiceState ABGroupUpdateObject = new MsnServiceState(PartnerScenario.GroupSave, "ABGroupUpdate", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABGroupUpdateObject); abService.ABGroupUpdateCompleted += delegate(object service, ABGroupUpdateCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABGroupUpdateObject, request)); } private void ABGroupDeleteAsync(ContactGroup contactGroup, ABGroupDeleteCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABGroupDelete", new MSNPSharpException("You don't have access right on this action anymore."))); return; } ABGroupDeleteRequestType request = new ABGroupDeleteRequestType(); request.abId = WebServiceConstants.MessengerIndividualAddressBookId; request.groupFilter = new groupFilterType(); request.groupFilter.groupIds = new string[] { contactGroup.Guid }; MsnServiceState ABGroupDeleteObject = new MsnServiceState(PartnerScenario.Timer, "ABGroupDelete", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABGroupDeleteObject); abService.ABGroupDeleteCompleted += delegate(object service, ABGroupDeleteCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABGroupDeleteObject, request)); } private void ABGroupContactAddAsync(Contact contact, ContactGroup group, ABGroupContactAddCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABGroupContactAdd", new MSNPSharpException("You don't have access right on this action anymore."))); return; } ABGroupContactAddRequestType request = new ABGroupContactAddRequestType(); request.abId = WebServiceConstants.MessengerIndividualAddressBookId; request.groupFilter = new groupFilterType(); request.groupFilter.groupIds = new string[] { group.Guid }; request.contacts = new ContactType[] { new ContactType() }; request.contacts[0].contactId = contact.Guid.ToString(); MsnServiceState ABGroupContactAddObject = new MsnServiceState(PartnerScenario.GroupSave, "ABGroupContactAdd", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABGroupContactAddObject); abService.ABGroupContactAddCompleted += delegate(object service, ABGroupContactAddCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABGroupContactAddObject, request)); } private void ABGroupContactDeleteAsync(Contact contact, ContactGroup group, ABGroupContactDeleteCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("ABGroupContactDelete", new MSNPSharpException("You don't have access right on this action anymore."))); return; } ABGroupContactDeleteRequestType request = new ABGroupContactDeleteRequestType(); request.abId = WebServiceConstants.MessengerIndividualAddressBookId; request.groupFilter = new groupFilterType(); request.groupFilter.groupIds = new string[] { group.Guid }; request.contacts = new ContactType[] { new ContactType() }; request.contacts[0].contactId = contact.Guid.ToString(); MsnServiceState ABGroupContactDelete = new MsnServiceState(PartnerScenario.GroupSave, "ABGroupContactDelete", true); ABServiceBinding abService = (ABServiceBinding)CreateService(MsnServiceType.AB, ABGroupContactDelete); abService.ABGroupContactDeleteCompleted += delegate(object service, ABGroupContactDeleteCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.AB, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(service, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.AB, ABGroupContactDelete, request)); } private void AddMemberAsync(Contact contact, ServiceName serviceName, RoleLists list, AddMemberCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("AddMember", new MSNPSharpException("You don't have access right on this action anymore."))); return; } // check whether the update is necessary if (contact.HasLists(list)) return; RoleId memberRole = ContactList.GetMemberRole(list); if (memberRole == RoleId.None) return; Service service = AddressBook.SelectTargetService(serviceName); if (service == null) { AddServiceAsync(serviceName, delegate { // RESURSIVE CALL AddMemberAsync(contact, serviceName, list, callback); }); return; } AddMemberRequestType addMemberRequest = new AddMemberRequestType(); addMemberRequest.serviceHandle = new HandleType(); addMemberRequest.serviceHandle.Id = service.Id.ToString(); addMemberRequest.serviceHandle.Type = serviceName; Membership memberShip = new Membership(); memberShip.MemberRole = memberRole; BaseMember member = null; // Abstract if (contact.ClientType == IMAddressInfoType.WindowsLive) { member = new PassportMember(); PassportMember passportMember = member as PassportMember; passportMember.PassportName = contact.Account; passportMember.State = MemberState.Accepted; passportMember.Type = MembershipType.Passport; } else if (contact.ClientType == IMAddressInfoType.Yahoo || contact.ClientType == IMAddressInfoType.OfficeCommunicator) { member = new EmailMember(); EmailMember emailMember = member as EmailMember; emailMember.State = MemberState.Accepted; emailMember.Type = MembershipType.Email; emailMember.Email = contact.Account; emailMember.Annotations = new Annotation[] { new Annotation() }; emailMember.Annotations[0].Name = AnnotationNames.MSN_IM_BuddyType; emailMember.Annotations[0].Value = (contact.ClientType == IMAddressInfoType.Yahoo) ? "32:" : "02:"; } else if (contact.ClientType == IMAddressInfoType.Telephone) { member = new PhoneMember(); PhoneMember phoneMember = member as PhoneMember; phoneMember.State = MemberState.Accepted; phoneMember.Type = MembershipType.Phone; phoneMember.PhoneNumber = contact.Account; } else if (contact.ClientType == IMAddressInfoType.Circle) { member = new CircleMember(); CircleMember circleMember = member as CircleMember; circleMember.Type = MembershipType.Circle; circleMember.State = MemberState.Accepted; circleMember.CircleId = contact.AddressBookId.ToString("D").ToLowerInvariant(); } if (member == null) return; memberShip.Members = new BaseMember[] { member }; addMemberRequest.memberships = new Membership[] { memberShip }; MsnServiceState AddMemberObject = new MsnServiceState(PartnerScenario.ContactMsgrAPI, "AddMember", true); SharingServiceBinding sharingService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, AddMemberObject); sharingService.AddMemberCompleted += delegate(object srv, AddMemberCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(sharingService, MsnServiceType.Sharing, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; // Update AB AddressBook.AddMemberhip(serviceName, contact.Account, contact.ClientType, memberRole, member); if (callback != null) { callback(srv, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(sharingService, MsnServiceType.Sharing, AddMemberObject, addMemberRequest)); } private void DeleteMemberAsync(Contact contact, ServiceName serviceName, RoleLists list, DeleteMemberCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("DeleteMember", new MSNPSharpException("You don't have access right on this action anymore."))); return; } // check whether the update is necessary if (!contact.HasLists(list)) return; RoleId memberRole = ContactList.GetMemberRole(list); if (memberRole == RoleId.None) return; Service service = AddressBook.SelectTargetService(serviceName); if (service == null) { AddServiceAsync(serviceName, delegate { // RESURSIVE CALL DeleteMemberAsync(contact, serviceName, list, callback); }); return; } DeleteMemberRequestType deleteMemberRequest = new DeleteMemberRequestType(); deleteMemberRequest.serviceHandle = new HandleType(); deleteMemberRequest.serviceHandle.Id = service.Id.ToString(); deleteMemberRequest.serviceHandle.Type = serviceName; Membership memberShip = new Membership(); memberShip.MemberRole = memberRole; BaseMember deleteMember = null; // BaseMember is an abstract type, so we cannot create a new instance. // If we have a MembershipId different from 0, just use it. Otherwise, use email or phone number. BaseMember baseMember = AddressBook.SelectBaseMember(serviceName, contact.Account, contact.ClientType, memberRole); int membershipId = (baseMember == null) ? 0 : baseMember.MembershipId; switch (contact.ClientType) { case IMAddressInfoType.WindowsLive: deleteMember = new PassportMember(); deleteMember.Type = (baseMember == null) ? MembershipType.Passport : baseMember.Type; deleteMember.State = (baseMember == null) ? MemberState.Accepted : baseMember.State; if (membershipId == 0) { (deleteMember as PassportMember).PassportName = contact.Account; } else { deleteMember.MembershipId = membershipId; deleteMember.MembershipIdSpecified = true; } break; case IMAddressInfoType.Yahoo: case IMAddressInfoType.OfficeCommunicator: deleteMember = new EmailMember(); deleteMember.Type = MembershipType.Email; deleteMember.State = (baseMember == null) ? MemberState.Accepted : baseMember.State; if (membershipId == 0) { (deleteMember as EmailMember).Email = contact.Account; } else { deleteMember.MembershipId = membershipId; deleteMember.MembershipIdSpecified = true; } break; case IMAddressInfoType.Telephone: deleteMember = new PhoneMember(); deleteMember.Type = MembershipType.Phone; deleteMember.State = (baseMember == null) ? MemberState.Accepted : baseMember.State; if (membershipId == 0) { (deleteMember as PhoneMember).PhoneNumber = contact.Account; } else { deleteMember.MembershipId = membershipId; deleteMember.MembershipIdSpecified = true; } break; case IMAddressInfoType.Circle: deleteMember = new CircleMember(); deleteMember.Type = MembershipType.Circle; deleteMember.State = (baseMember == null) ? MemberState.Accepted : baseMember.State; (deleteMember as CircleMember).CircleId = contact.AddressBookId.ToString("D").ToLowerInvariant(); break; } memberShip.Members = new BaseMember[] { deleteMember }; deleteMemberRequest.memberships = new Membership[] { memberShip }; MsnServiceState DeleteMemberObject = new MsnServiceState(PartnerScenario.ContactMsgrAPI, "DeleteMember", true); SharingServiceBinding sharingService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, DeleteMemberObject); sharingService.DeleteMemberCompleted += delegate(object srv, DeleteMemberCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(sharingService, MsnServiceType.Sharing, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; // Update AB AddressBook.RemoveMemberhip(serviceName, contact.Account, contact.ClientType, memberRole); if (callback != null) { callback(srv, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(sharingService, MsnServiceType.Sharing, DeleteMemberObject, deleteMemberRequest)); } private void CreateCircleAsync(string circleName, CreateCircleCompletedEventHandler callback) { //This is M$ style, you will never guess out the meaning of these numbers. ContentInfoType properties = new ContentInfoType(); properties.Domain = 1; properties.HostedDomain = Contact.DefaultHostDomain; properties.Type = 2; properties.MembershipAccess = 0; properties.IsPresenceEnabled = true; properties.RequestMembershipOption = 2; properties.DisplayName = circleName; CreateCircleRequestType request = new CreateCircleRequestType(); request.properties = properties; request.callerInfo = new callerInfoType(); request.callerInfo.PublicDisplayName = NSMessageHandler.Owner.Name == string.Empty ? NSMessageHandler.Owner.Account : NSMessageHandler.Owner.Name; MsnServiceState createCircleObject = new MsnServiceState(PartnerScenario.CircleSave, "CreateCircle", true); SharingServiceBinding sharingService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, createCircleObject); sharingService.CreateCircleCompleted += delegate(object sender, CreateCircleCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(sharingService, MsnServiceType.Sharing, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (callback != null) { callback(sender, e); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(sharingService, MsnServiceType.Sharing, createCircleObject, request)); } private void AddServiceAsync(ServiceName serviceName, AddServiceCompletedEventHandler callback) { if (NSMessageHandler.MSNTicket == MSNTicket.Empty || AddressBook == null) { OnServiceOperationFailed(this, new ServiceOperationFailedEventArgs("AddService", new MSNPSharpException("You don't have access right on this action anymore."))); } else { AddServiceRequestType r = new AddServiceRequestType(); r.serviceInfo = new InfoType(); r.serviceInfo.Handle = new HandleType(); r.serviceInfo.Handle.Type = serviceName; r.serviceInfo.Handle.ForeignId = String.Empty; r.serviceInfo.InverseRequired = true; MsnServiceState addServiceObject = new MsnServiceState(PartnerScenario.CircleSave, "AddService", true); SharingServiceBinding abService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, addServiceObject); abService.AddServiceCompleted += delegate(object service, AddServiceCompletedEventArgs e) { OnAfterCompleted(new ServiceOperationEventArgs(abService, MsnServiceType.Sharing, e)); if (e.Cancelled || NSMessageHandler.MSNTicket == MSNTicket.Empty) return; if (e.Error == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, serviceName + "=" + e.Result.AddServiceResult + " created..."); // Update service membership... msRequest(PartnerScenario.BlockUnblock, delegate { if (callback != null) callback(abService, e); }); } }; RunAsyncMethod(new BeforeRunAsyncMethodEventArgs(abService, MsnServiceType.Sharing, addServiceObject, r)); } } } };
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; using System; using System.Collections.Generic; using System.IO; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests { [TestFixture] public class InventoryArchiveLoadPathTests : InventoryArchiveTestCase { /// <summary> /// Test loading an IAR to various different inventory paths. /// </summary> [Test] public void TestLoadIarToInventoryPaths() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); UserAccountHelpers.CreateUserWithInventory(scene, m_uaMT, "meowfood"); UserAccountHelpers.CreateUserWithInventory(scene, m_uaLL1, "hampshire"); archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/", "meowfood", m_iarStream); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, m_item1Name); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // Now try loading to a root child folder UserInventoryHelpers.CreateInventoryFolder(scene.InventoryService, m_uaMT.PrincipalID, "xA", false); MemoryStream archiveReadStream = new MemoryStream(m_iarStream.ToArray()); archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "xA", "meowfood", archiveReadStream); InventoryItemBase foundItem2 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, "xA/" + m_item1Name); Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2"); // Now try loading to a more deeply nested folder UserInventoryHelpers.CreateInventoryFolder(scene.InventoryService, m_uaMT.PrincipalID, "xB/xC", false); archiveReadStream = new MemoryStream(archiveReadStream.ToArray()); archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "xB/xC", "meowfood", archiveReadStream); InventoryItemBase foundItem3 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, "xB/xC/" + m_item1Name); Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3"); } /// <summary> /// Test that things work when the load path specified starts with a slash /// </summary> [Test] public void TestLoadIarPathStartsWithSlash() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); Scene scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); UserAccountHelpers.CreateUserWithInventory(scene, m_uaMT, "password"); archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/Objects", "password", m_iarStream); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath( scene.InventoryService, m_uaMT.PrincipalID, "/Objects/" + m_item1Name); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1 in TestLoadIarFolderStartsWithSlash()"); } [Test] public void TestLoadIarPathWithEscapedChars() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); string itemName = "You & you are a mean/man/"; string humanEscapedItemName = @"You & you are a mean\/man\/"; string userPassword = "meowfood"; InventoryArchiverModule archiverModule = new InventoryArchiverModule(); Scene scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(scene, archiverModule); // Create user string userFirstName = "Jock"; string userLastName = "Stirrup"; UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); UserAccountHelpers.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood"); // Create asset SceneObjectGroup object1; SceneObjectPart part1; { string partName = "part name"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); part1 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = partName; object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); } UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); scene.AssetService.Store(asset1); // Create item UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = asset1.FullID; item1.ID = item1Id; InventoryFolderBase objsFolder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, "Objects")[0]; item1.Folder = objsFolder.ID; scene.AddInventoryItem(item1); MemoryStream archiveWriteStream = new MemoryStream(); archiverModule.OnInventoryArchiveSaved += SaveCompleted; mre.Reset(); archiverModule.ArchiveInventory( Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream); mre.WaitOne(60000, false); // LOAD ITEM MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath( scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // Assert.That( // foundItem1.CreatorId, Is.EqualTo(userUuid), // "Loaded item non-uuid creator doesn't match that of the loading user"); Assert.That( foundItem1.Name, Is.EqualTo(itemName), "Loaded item name doesn't match saved name"); } /// <summary> /// Test replication of an archive path to the user's inventory. /// </summary> [Test] public void TestNewIarPath() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); Scene scene = new SceneHelpers().SetupScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene); Dictionary<string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); HashSet<InventoryNodeBase> nodesLoaded = new HashSet<InventoryNodeBase>(); string folder1Name = "1"; string folder2aName = "2a"; string folder2bName = "2b"; string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); string folder2aArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2aName, UUID.Random()); string folder2bArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2bName, UUID.Random()); string iarPath1 = string.Join("", new string[] { folder1ArchiveName, folder2aArchiveName }); string iarPath2 = string.Join("", new string[] { folder1ArchiveName, folder2bArchiveName }); { // Test replication of path1 new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false) .ReplicateArchivePathToUserInventory( iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID), foldersCreated, nodesLoaded); List<InventoryFolderBase> folder1Candidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); Assert.That(folder1Candidates.Count, Is.EqualTo(1)); InventoryFolderBase folder1 = folder1Candidates[0]; List<InventoryFolderBase> folder2aCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, folder1, folder2aName); Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); } { // Test replication of path2 new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false) .ReplicateArchivePathToUserInventory( iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID), foldersCreated, nodesLoaded); List<InventoryFolderBase> folder1Candidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); Assert.That(folder1Candidates.Count, Is.EqualTo(1)); InventoryFolderBase folder1 = folder1Candidates[0]; List<InventoryFolderBase> folder2aCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, folder1, folder2aName); Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); List<InventoryFolderBase> folder2bCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, folder1, folder2bName); Assert.That(folder2bCandidates.Count, Is.EqualTo(1)); } } /// <summary> /// Test replication of a partly existing archive path to the user's inventory. This should create /// a duplicate path without the merge option. /// </summary> [Test] public void TestPartExistingIarPath() { TestHelpers.InMethod(); //log4net.Config.XmlConfigurator.Configure(); Scene scene = new SceneHelpers().SetupScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene); string folder1ExistingName = "a"; string folder2Name = "b"; InventoryFolderBase folder1 = UserInventoryHelpers.CreateInventoryFolder( scene.InventoryService, ua1.PrincipalID, folder1ExistingName, false); string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false) .ReplicateArchivePathToUserInventory( itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>()); List<InventoryFolderBase> folder1PostCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); Assert.That(folder1PostCandidates.Count, Is.EqualTo(2)); // FIXME: Temporarily, we're going to do something messy to make sure we pick up the created folder. InventoryFolderBase folder1Post = null; foreach (InventoryFolderBase folder in folder1PostCandidates) { if (folder.ID != folder1.ID) { folder1Post = folder; break; } } // Assert.That(folder1Post.ID, Is.EqualTo(folder1.ID)); List<InventoryFolderBase> folder2PostCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, folder1Post, "b"); Assert.That(folder2PostCandidates.Count, Is.EqualTo(1)); } /// <summary> /// Test replication of a partly existing archive path to the user's inventory. This should create /// a merged path. /// </summary> [Test] public void TestMergeIarPath() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); Scene scene = new SceneHelpers().SetupScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene); string folder1ExistingName = "a"; string folder2Name = "b"; InventoryFolderBase folder1 = UserInventoryHelpers.CreateInventoryFolder( scene.InventoryService, ua1.PrincipalID, folder1ExistingName, false); string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, folder1ExistingName, (Stream)null, true) .ReplicateArchivePathToUserInventory( itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>()); List<InventoryFolderBase> folder1PostCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); Assert.That(folder1PostCandidates.Count, Is.EqualTo(1)); Assert.That(folder1PostCandidates[0].ID, Is.EqualTo(folder1.ID)); List<InventoryFolderBase> folder2PostCandidates = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, folder1PostCandidates[0], "b"); Assert.That(folder2PostCandidates.Count, Is.EqualTo(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; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class SDMSamplesTests : XLinqTestCase { public partial class SDM_Attribute : XLinqTestCase { public void AttributeConstructor() { string value = "bar"; // Name/value constructor. try { XAttribute a = new XAttribute(null, value); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } try { XAttribute a = new XAttribute("foo", null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Codepaths for special-casing xmlns namespace XName name = XName.Get("xmlns", string.Empty); XAttribute att1 = new XAttribute(name, value); Validate.AttributeNameAndValue(att1, "xmlns", value); name = XName.Get("xmlns", "namespacename"); att1 = new XAttribute(name, value); Validate.AttributeNameAndValue(att1, "{namespacename}xmlns", value); name = XName.Get("foo", string.Empty); att1 = new XAttribute(name, value); Validate.AttributeNameAndValue(att1, "foo", value); name = XName.Get("foo", "namespacename"); att1 = new XAttribute(name, value); Validate.AttributeNameAndValue(att1, "{namespacename}foo", value); // Copy constructor. try { XAttribute a = new XAttribute((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } XAttribute att2 = new XAttribute(att1); Validate.AttributeNameAndValue(att2, att1.Name.ToString(), att1.Value); } /// <summary> /// Tests EmptySequence on XAttribute. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "AttributeEmptySequence")] public void AttributeEmptySequence() { Validate.Enumerator(XAttribute.EmptySequence, new XAttribute[0]); Validate.Enumerator(XAttribute.EmptySequence, new XAttribute[0]); } /// <summary> /// Tests IsNamespaceDeclaration on XAttribute. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "AttributeIsNamespaceDeclaration")] public void AttributeIsNamespaceDeclaration() { XAttribute att1 = new XAttribute("{http://bogus}name", "value"); XAttribute att2 = new XAttribute("{http://www.w3.org/2000/xmlns/}name", "value"); Validate.IsEqual(att1.IsNamespaceDeclaration, false); Validate.IsEqual(att2.IsNamespaceDeclaration, true); } /// <summary> /// Tests Parent on XAttribute. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "AttributeParent")] public void AttributeParent() { XAttribute a = new XAttribute("att-name", "value"); XElement e = new XElement("elem-name"); Validate.IsNull(a.Parent); e.Add(a); Validate.IsEqual(a.Parent, e); e.RemoveAttributes(); Validate.IsNull(a.Parent); } /// <summary> /// Validate behavior of the Value property on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeValue")] public void AttributeValue() { XAttribute a = new XAttribute("foo", 10m); Validate.IsEqual(a.Value, "10"); try { a.Value = null; Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } a.Value = "100"; Validate.IsEqual(a.Value, "100"); } /// <summary> /// Validates the behavior of the Remove method on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeRemove")] public void AttributeRemove() { XElement e = new XElement("element"); XAttribute a = new XAttribute("attribute", "value"); // Can't remove when no parent. try { a.Remove(); Validate.ExpectedThrow(typeof(InvalidOperationException)); } catch (Exception ex) { Validate.Catch(ex, typeof(InvalidOperationException)); } e.Add(a); Validate.Count(e.Attributes(), 1); a.Remove(); Validate.Count(e.Attributes(), 0); } /// <summary> /// Validates the explicit string conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToString")] public void AttributeExplicitToString() { XAttribute e2 = new XAttribute("x", string.Empty); XAttribute e3 = new XAttribute("x", 10.0); string s0 = (string)((XAttribute)null); string s2 = (string)e2; string s3 = (string)e3; Validate.IsNull(s0); Validate.String(s2, string.Empty); Validate.String(s3, "10"); } /// <summary> /// Validates the explicit boolean conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToBoolean")] public void AttributeExplicitToBoolean() { // Calling explicit operator with null should result in exception. try { bool b = (bool)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "true"); XAttribute e4 = new XAttribute("x", "false"); XAttribute e5 = new XAttribute("x", "0"); XAttribute e6 = new XAttribute("x", "1"); try { bool b1 = (bool)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { bool b2 = (bool)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } Validate.IsEqual((bool)e3, true); Validate.IsEqual((bool)e4, false); Validate.IsEqual((bool)e5, false); Validate.IsEqual((bool)e6, true); } /// <summary> /// Validates the explicit int32 conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToInt32")] public void AttributeExplicitToInt32() { // Calling explicit operator with null should result in exception. try { int i = (int)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "2147483648"); XAttribute e4 = new XAttribute("x", "5"); try { int i1 = (int)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { int i2 = (int)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { int i3 = (int)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((int)e4, 5); } /// <summary> /// Validates the explicit uint32 conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToUInt32")] public void AttributeExplicitToUInt32() { // Calling explicit operator with null should result in exception. try { uint i = (uint)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "4294967296"); XAttribute e4 = new XAttribute("x", "5"); try { uint i1 = (uint)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { uint i2 = (uint)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { uint i3 = (uint)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((uint)e4, 5u); } /// <summary> /// Validates the explicit int64 conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToInt64")] public void AttributeExplicitToInt64() { // Calling explicit operator with null should result in exception. try { long i = (long)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "18446744073709551616"); XAttribute e4 = new XAttribute("x", "5"); try { long i1 = (long)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { long i2 = (long)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { long i3 = (long)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((long)e4, 5L); } /// <summary> /// Validates the explicit uint64 conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToUInt64")] public void AttributeExplicitToUInt64() { // Calling explicit operator with null should result in exception. try { ulong i = (ulong)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "18446744073709551616"); XAttribute e4 = new XAttribute("x", "5"); try { ulong i1 = (ulong)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { ulong i2 = (ulong)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { ulong i3 = (ulong)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((ulong)e4, 5UL); } /// <summary> /// Validates the explicit float conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToFloat")] public void AttributeExplicitToFloat() { // Calling explicit operator with null should result in exception. try { float f = (float)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "5e+500"); XAttribute e4 = new XAttribute("x", "5.0"); try { float f1 = (float)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { float f2 = (float)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { float i3 = (float)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((float)e4, 5.0f); } /// <summary> /// Validates the explicit double conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToDouble")] public void AttributeExplicitToDouble() { // Calling explicit operator with null should result in exception. try { double f = (double)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "5e+5000"); XAttribute e4 = new XAttribute("x", "5.0"); try { double f1 = (double)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { double f2 = (double)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { double f3 = (double)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((double)e4, 5.0); } /// <summary> /// Validates the explicit decimal conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToDecimal")] public void AttributeExplicitToDecimal() { // Calling explicit operator with null should result in exception. try { decimal d = (decimal)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "111111111111111111111111111111111111111111111111"); XAttribute e4 = new XAttribute("x", "5.0"); try { decimal d1 = (decimal)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { decimal d2 = (decimal)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { decimal d3 = (decimal)e3; Validate.ExpectedThrow(typeof(OverflowException)); } catch (Exception ex) { Validate.Catch(ex, typeof(OverflowException)); } Validate.IsEqual((decimal)e4, 5m); } /// <summary> /// Validates the explicit DateTime conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToDateTime")] public void AttributeExplicitToDateTime() { // Calling explicit operator with null should result in exception. try { DateTime d = (DateTime)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "1968-01-07"); try { DateTime d1 = (DateTime)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { DateTime d2 = (DateTime)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } Validate.IsEqual((DateTime)e3, new DateTime(1968, 1, 7)); } /// <summary> /// Validates the explicit TimeSpan conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToTimeSpan")] public void AttributeExplicitToTimeSpan() { // Calling explicit operator with null should result in exception. try { TimeSpan d = (TimeSpan)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", "PT1H2M3S"); try { TimeSpan d1 = (TimeSpan)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { TimeSpan d2 = (TimeSpan)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } Validate.IsEqual((TimeSpan)e3, new TimeSpan(1, 2, 3)); } /// <summary> /// Validates the explicit guid conversion operator on XAttribute. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToGuId")] public void AttributeExplicitToGuid() { // Calling explicit operator with null should result in exception. try { Guid g = (Guid)((XAttribute)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } string guid = "2b67e9fb-97ad-4258-8590-8bc8c2d32df5"; // Test various values. XAttribute e1 = new XAttribute("x", string.Empty); XAttribute e2 = new XAttribute("x", "bogus"); XAttribute e3 = new XAttribute("x", guid); try { Guid g1 = (Guid)e1; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } try { Guid g2 = (Guid)e2; Validate.ExpectedThrow(typeof(FormatException)); } catch (Exception ex) { Validate.Catch(ex, typeof(FormatException)); } Validate.IsEqual((Guid)e3, new Guid(guid)); } /// <summary> /// Validates the explicit conversion operators on XAttribute /// for nullable value types. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "AttributeExplicitToNullables")] public void AttributeExplicitToNullables() { string guid = "cd8d69ed-fef9-4283-aaf4-216463e4496f"; bool? b = (bool?)new XAttribute("x", true); int? i = (int?)new XAttribute("x", 5); uint? u = (uint?)new XAttribute("x", 5); long? l = (long?)new XAttribute("x", 5); ulong? ul = (ulong?)new XAttribute("x", 5); float? f = (float?)new XAttribute("x", 5); double? n = (double?)new XAttribute("x", 5); decimal? d = (decimal?)new XAttribute("x", 5); DateTime? dt = (DateTime?)new XAttribute("x", "1968-01-07"); TimeSpan? ts = (TimeSpan?)new XAttribute("x", "PT1H2M3S"); Guid? g = (Guid?)new XAttribute("x", guid); Validate.IsEqual(b.Value, true); Validate.IsEqual(i.Value, 5); Validate.IsEqual(u.Value, 5u); Validate.IsEqual(l.Value, 5L); Validate.IsEqual(ul.Value, 5uL); Validate.IsEqual(f.Value, 5.0f); Validate.IsEqual(n.Value, 5.0); Validate.IsEqual(d.Value, 5.0m); Validate.IsEqual(dt.Value, new DateTime(1968, 1, 7)); Validate.IsEqual(ts.Value, new TimeSpan(1, 2, 3)); Validate.IsEqual(g.Value, new Guid(guid)); b = (bool?)((XAttribute)null); i = (int?)((XAttribute)null); u = (uint?)((XAttribute)null); l = (long?)((XAttribute)null); ul = (ulong?)((XAttribute)null); f = (float?)((XAttribute)null); n = (double?)((XAttribute)null); d = (decimal?)((XAttribute)null); dt = (DateTime?)((XAttribute)null); ts = (TimeSpan?)((XAttribute)null); g = (Guid?)((XAttribute)null); Validate.IsNull(b); Validate.IsNull(i); Validate.IsNull(u); Validate.IsNull(l); Validate.IsNull(ul); Validate.IsNull(f); Validate.IsNull(n); Validate.IsNull(d); Validate.IsNull(dt); Validate.IsNull(ts); Validate.IsNull(g); } } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataGenericParam : MetaDataObject, IMetaDataNormalize { // // State // private short m_number; private GenericParameterAttributes m_flags; private IMetaDataTypeOrMethodDef m_owner; private String m_name; private List<IMetaDataTypeDefOrRef> m_genericParamConstraints; // // Constructor Methods // private MetaDataGenericParam( int index ) : base( TokenType.GenericParam, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable<T> internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataGenericParam( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader ownerReader = ts.m_columns[2].m_reader; int ownerIndex; m_number = reader.ReadInt16(); m_flags = (GenericParameterAttributes) reader.ReadInt16(); ownerIndex = ownerReader ( reader ); m_name = parser.readIndexAsString ( reader ); m_owner = parser.getTypeOrMethodDef( ownerIndex ); if(m_owner is MetaDataTypeDefinition) { ((MetaDataTypeDefinition)m_owner).AddGenericParam( this ); } else if(m_owner is MetaDataMethod) { ((MetaDataMethod)m_owner).AddGenericParam( this ); } else { throw IllegalMetaDataFormatException.Create( "Unknown owner of GenericParam: {0}", m_owner ); } } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfTypeDefinitions: if(m_owner is MetaDataTypeDefinition) { Normalized.MetaDataGenericTypeParam param = new Normalized.MetaDataGenericTypeParam( context.GetTypeFromContext(), m_token ); param.m_number = m_number; param.m_flags = m_flags; param.m_name = m_name; return param; } break; case MetaDataNormalizationPhase.CreationOfMethodDefinitions: if(m_owner is MetaDataMethod) { Normalized.MetaDataGenericMethodParam param = new Normalized.MetaDataGenericMethodParam( (Normalized.MetaDataMethodGeneric)context.GetMethodFromContext(), m_token ); param.m_number = m_number; param.m_flags = m_flags; param.m_name = m_name; return param; } break; } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataGenericParam param = (Normalized.MetaDataGenericParam)obj; switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfTypeNormalization: { context.GetNormalizedObjectList( m_genericParamConstraints, out param.m_genericParamConstraints, MetaDataNormalizationMode.Default ); } return; case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out param.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } //--// internal void AddGenericParamConstraint( IMetaDataTypeDefOrRef constraint ) { if(m_genericParamConstraints == null) { m_genericParamConstraints = new List<IMetaDataTypeDefOrRef>( 2 ); } m_genericParamConstraints.Add( constraint ); } // // Access Methods // public short Number { get { return m_number; } } public GenericParameterAttributes Flags { get { return m_flags; } } public IMetaDataTypeOrMethodDef Owner { get { return m_owner; } } public String Name { get { return m_name; } } public List<IMetaDataTypeDefOrRef> GenericParamConstraints { get { return m_genericParamConstraints; } } // // Debug Methods // public override String ToString() { return "MetaDataGenericParam(" + m_name + ")"; } public override String ToStringLong() { return "MetaDataGenericParam(" + m_number + "," + m_flags.ToString( "x" ) + "," + m_owner + "," + m_name + ")"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using CoreGraphics; using UIKit; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; namespace Xamarin.Forms.Platform.iOS { [Flags] public enum VisualElementRendererFlags { Disposed = 1 << 0, AutoTrack = 1 << 1, AutoPackage = 1 << 2 } public class VisualElementRenderer<TElement> : UIView, IVisualElementRenderer, IEffectControlProvider where TElement : VisualElement { readonly UIColor _defaultColor = UIColor.Clear; readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>(); readonly PropertyChangedEventHandler _propertyChangedHandler; EventTracker _events; VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack; VisualElementPackager _packager; VisualElementTracker _tracker; protected VisualElementRenderer() : base(CGRect.Empty) { _propertyChangedHandler = OnElementPropertyChanged; BackgroundColor = UIColor.Clear; } // prevent possible crashes in overrides public sealed override UIColor BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; } } public TElement Element { get; private set; } protected bool AutoPackage { get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; } set { if (value) _flags |= VisualElementRendererFlags.AutoPackage; else _flags &= ~VisualElementRendererFlags.AutoPackage; } } protected bool AutoTrack { get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; } set { if (value) _flags |= VisualElementRendererFlags.AutoTrack; else _flags &= ~VisualElementRendererFlags.AutoTrack; } } public static void RegisterEffect(Effect effect, UIView container, UIView control = null) { var platformEffect = effect as PlatformEffect; if (platformEffect == null) return; platformEffect.Container = container; platformEffect.Control = control; } void IEffectControlProvider.RegisterEffect(Effect effect) { var platformEffect = effect as PlatformEffect; if (platformEffect != null) OnRegisterEffect(platformEffect); } VisualElement IVisualElementRenderer.Element { get { return Element; } } event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged { add { _elementChangedHandlers.Add(value); } remove { _elementChangedHandlers.Remove(value); } } public virtual SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { return NativeView.GetSizeRequest(widthConstraint, heightConstraint); } public UIView NativeView { get { return this; } } void IVisualElementRenderer.SetElement(VisualElement element) { SetElement((TElement)element); } public void SetElementSize(Size size) { Layout.LayoutChildIntoBoundingRegion(Element, new Rectangle(Element.X, Element.Y, size.Width, size.Height)); } public virtual UIViewController ViewController { get { return null; } } public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged; public void SetElement(TElement element) { var oldElement = Element; Element = element; if (oldElement != null) oldElement.PropertyChanged -= _propertyChangedHandler; if (element != null) { if (element.BackgroundColor != Color.Default || (oldElement != null && element.BackgroundColor != oldElement.BackgroundColor)) SetBackgroundColor(element.BackgroundColor); UpdateClipToBounds(); if (_tracker == null) { _tracker = new VisualElementTracker(this); _tracker.NativeControlUpdated += (sender, e) => UpdateNativeWidget(); } if (AutoPackage && _packager == null) { _packager = new VisualElementPackager(this); _packager.Load(); } if (AutoTrack && _events == null) { _events = new EventTracker(this); _events.LoadEvents(this); } element.PropertyChanged += _propertyChangedHandler; } OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element)); if (element != null) SendVisualElementInitialized(element, this); EffectUtilities.RegisterEffectControlProvider(this, oldElement, element); if (Element != null && !string.IsNullOrEmpty(Element.AutomationId)) SetAutomationId(Element.AutomationId); } public override CGSize SizeThatFits(CGSize size) { return new CGSize(0, 0); } protected override void Dispose(bool disposing) { if ((_flags & VisualElementRendererFlags.Disposed) != 0) return; _flags |= VisualElementRendererFlags.Disposed; if (disposing) { if (_events != null) { _events.Dispose(); _events = null; } if (_tracker != null) { _tracker.Dispose(); _tracker = null; } if (_packager != null) { _packager.Dispose(); _packager = null; } Platform.SetRenderer(Element, null); SetElement(null); Element = null; } base.Dispose(disposing); } protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e) { var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement); for (var i = 0; i < _elementChangedHandlers.Count; i++) _elementChangedHandlers[i](this, args); var changed = ElementChanged; if (changed != null) changed(this, e); } protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) SetBackgroundColor(Element.BackgroundColor); else if (e.PropertyName == Layout.IsClippedToBoundsProperty.PropertyName) UpdateClipToBounds(); } protected virtual void OnRegisterEffect(PlatformEffect effect) { effect.Container = this; } protected virtual void SetAutomationId(string id) { AccessibilityIdentifier = id; } protected virtual void SetBackgroundColor(Color color) { if (color == Color.Default) BackgroundColor = _defaultColor; else BackgroundColor = color.ToUIColor(); } protected virtual void UpdateNativeWidget() { } internal virtual void SendVisualElementInitialized(VisualElement element, UIView nativeView) { element.SendViewInitialized(nativeView); } void UpdateClipToBounds() { var clippableLayout = Element as Layout; if (clippableLayout != null) ClipsToBounds = clippableLayout.IsClippedToBounds; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; /* * This class accumulates the information about the tested server, * and produces the report. */ class Report { /* * Connection name (server name). */ internal string ConnName { get { return connName; } set { connName = value; } } /* * Connection port. */ internal int ConnPort { get { return connPort; } set { connPort = value; } } /* * Server name sent in the SNI extension. This may be null if * no SNI extension was sent. */ internal string SNI { get { return sni; } set { sni = value; } } /* * List of supported SSLv2 cipher suites, in the order returned * by the server (which is purely advisory, since selection is * done by the client). It is null if SSLv2 is not supported. */ internal int[] SSLv2CipherSuites { get { return ssl2Suites; } set { ssl2Suites = value; } } /* * Certificate sent by the server if SSLv2 is supported (null * otherwise). It is reported as a chain of length 1. */ internal X509Chain SSLv2Chain { get { return ssl2Chain; } } /* * List of supported cipher suites, indexed by protocol version. * This map contains information for version SSL 3.0 and more. */ internal IDictionary<int, SupportedCipherSuites> CipherSuites { get { return suites; } } /* * Set to true if we had to shorten our ClientHello messages * (this indicates a server with a fixed, small buffer for * incoming ClientHello). */ internal bool NeedsShortHello { get { return shortHello; } set { shortHello = value; } } /* * Set to true if we had to suppress extensions from our * ClientHello (flawed server that does not support extensions). */ internal bool NoExtensions { get { return noExts; } set { noExts = value; } } /* * Set to true if the server, at some point, agreed to use * Deflate compression. */ internal bool DeflateCompress { get { return compress; } set { compress = value; } } /* * Set to true if the server appears to support secure * renegotiation (at least, it understands and returns an empty * extension; this does not demonstrate that the server would * accept an actual renegotiation, but if it does, then chances * are that it will tag it with the proper extension value). */ internal bool SupportsSecureRenegotiation { get { return doesRenego; } set { doesRenego = value; } } /* * Set the server time offset (serverTime - clientTime), in * milliseconds. * * Int64.MinValue means that the server sends 0 (the standard * method to indicate that the clock is not available). * * Int64.MaxValue means that the server sends random bytes * in the time field (non-standard, but widespread because * OpenSSL does that by default since September 2013). */ internal long ServerTimeOffset { get { return serverTimeOffset; } set { serverTimeOffset = value; } } /* * Minimal size (in bits) of DH parameters sent by server. If * server never used DHE or SRP, then this is 0. */ internal int MinDHSize { get { return minDHSize; } set { minDHSize = value; } } /* * Minimal size (in bits) of ECDH parameters sent by server. If * server never used ECDHE, then this is 0. This value is for * handshakes where the client DID NOT send a "supported curve" * extension. */ internal int MinECSize { get { return minECSize; } set { minECSize = value; } } /* * Minimal size (in bits) of ECDH parameters sent by server. If * server never used ECDHE, then this is 0. This value is for * handshakes where the client sent a "supported curve" extension. */ internal int MinECSizeExt { get { return minECSizeExt; } set { minECSizeExt = value; } } /* * Named curves used by the server for ECDH parameters. */ internal SSLCurve[] NamedCurves { get { return namedCurves; } set { namedCurves = value; } } /* * List of EC suites that the server supports when the client * does not send a Supported Elliptic Curves extension. The * list is not in any specific order. */ internal int[] SpontaneousEC { get { return spontaneousEC; } set { spontaneousEC = value; } } /* * Named curves spontaneously used by the server for ECDH * parameters. These are the curves that the server elected to * use in the absence of a "supported elliptic curves" extension * from the client. */ internal SSLCurve[] SpontaneousNamedCurves { get { return spontaneousNamedCurves; } set { spontaneousNamedCurves = value; } } /* * If non-zero, then this is the size of the "explicit prime" * curve selected by the server. */ internal int CurveExplicitPrime { get { return curveExplicitPrime; } set { curveExplicitPrime = value; } } /* * If non-zero, then this is the size of the "explicit char2" * curve selected by the server. */ internal int CurveExplicitChar2 { get { return curveExplicitChar2; } set { curveExplicitChar2 = value; } } /* * Set to true if one ServerKeyExchange message (at least) could * not be fully decoded. */ internal bool UnknownSKE { get { return unknownSKE; } set { unknownSKE = value; } } /* * Get all certificate chains gathered so far. */ internal X509Chain[] AllChains { get { return M.ToValueArray(chains); } } /* * The warnings aggregated after analysis. The map is indexed * by warning identifier; map values are explicit messsages. */ internal IDictionary<string, string> Warnings { get { return warnings; } } /* * If true, then the report will include the whole certificates * sent by the server (PEM format). */ internal bool ShowCertPEM { get { return withPEM; } set { withPEM = value; } } string connName; int connPort; string sni; int[] ssl2Suites; X509Chain ssl2Chain; bool shortHello; bool noExts; IDictionary<int, SupportedCipherSuites> suites; IDictionary<string, X509Chain> chains; bool compress; long serverTimeOffset; bool doesRenego; int minDHSize; int minECSize; int minECSizeExt; SSLCurve[] namedCurves; int[] spontaneousEC; SSLCurve[] spontaneousNamedCurves; int curveExplicitPrime; int curveExplicitChar2; bool unknownSKE; IDictionary<string, string> warnings; bool withPEM; /* * Create an empty report instance. */ internal Report() { suites = new SortedDictionary<int, SupportedCipherSuites>(); chains = new SortedDictionary<string, X509Chain>( StringComparer.Ordinal); serverTimeOffset = Int64.MinValue; } /* * Set the cipher suites supported for a specific protocol version * (SSLv3+). */ internal void SetCipherSuites(int version, SupportedCipherSuites scs) { suites[version] = scs; } /* * Record a certificate sent by a SSLv2 server. The certificate * is alone. */ internal void SetSSLv2Certificate(byte[] ssl2Cert) { if (ssl2Cert == null) { ssl2Chain = null; } else { ssl2Chain = X509Chain.Make( new byte[][] { ssl2Cert }, true); } } /* * Record a new certificate chain sent by the server. Duplicates * are merged. */ internal void AddServerChain(byte[][] chain) { X509Chain xc = X509Chain.Make(chain, true); chains[xc.Hash] = xc; } /* * Test whether a given named curve is part of the "spontaneous" * named curves. */ bool IsSpontaneous(SSLCurve sc) { if (spontaneousNamedCurves == null) { return false; } for (int i = 0; i < spontaneousNamedCurves.Length; i ++) { if (sc.Id == spontaneousNamedCurves[i].Id) { return true; } } return false; } /* * Analyse data and compute the list of relevant warnings. */ internal void Analyse() { warnings = new SortedDictionary<string, string>( StringComparer.Ordinal); if (ssl2Suites != null && ssl2Suites.Length > 0) { warnings["PV002"] = "Server supports SSL 2.0."; } if (suites.ContainsKey(M.SSLv30)) { warnings["PV003"] = "Server supports SSL 3.0."; } if (unknownSKE) { warnings["SK001"] = "Some Server Key Exchange messages" + " could not be processed."; } if (minDHSize > 0 && minDHSize < 2048) { warnings["SK002"] = "Server uses DH parameters smaller" + " than 2048 bits."; } if (minECSize > 0 && minECSize < 192) { warnings["SK003"] = "Server chooses ECDH parameters" + " smaller than 192 bits."; } if (minECSizeExt > 0 && minECSizeExt < 192) { warnings["SK004"] = "Server supports ECDH parameters" + " smaller than 192 bits (if requested)."; } if (NeedsShortHello) { warnings["PV001"] = "Server needs short ClientHello."; } if (NoExtensions) { warnings["PV004"] = "Server does not tolerate extensions."; } if (DeflateCompress) { warnings["CP001"] = "Server supports compression."; } bool hasCS0 = false; bool hasCS1 = false; bool hasCS2 = false; bool hasCSX = false; bool hasRC4 = false; bool hasNoFS = false; foreach (int pv in suites.Keys) { SupportedCipherSuites scs = suites[pv]; foreach (int s in scs.Suites) { CipherSuite cs; if (CipherSuite.ALL.TryGetValue(s, out cs)) { switch (cs.Strength) { case 0: hasCS0 = true; break; case 1: hasCS1 = true; break; case 2: hasCS2 = true; break; } if (cs.IsRC4) { hasRC4 = true; } if (!cs.HasForwardSecrecy) { hasNoFS = true; } } else { hasCSX = true; } } } if (hasCS0) { warnings["CS001"] = "Server supports unencrypted cipher suites."; } if (hasCS1) { warnings["CS002"] = "Server supports very weak" + " cipher suites (40 bits)."; } if (hasCS2) { warnings["CS003"] = "Server supports weak" + " cipher suites (56 bits)."; } if (hasCSX) { warnings["CS004"] = "Server supports unrecognized" + " cipher suites (unknown strength)."; } if (hasRC4) { warnings["CS005"] = "Server supports RC4."; } if (hasNoFS) { warnings["CS006"] = "Server supports cipher suites" + " with no forward secrecy."; } if (!doesRenego) { warnings["RN001"] = "Server does not support" + " secure renegotiation."; } bool hasBadSignHash = false; foreach (X509Chain xchain in chains.Values) { string[] shs = xchain.SignHashes; if (shs == null) { continue; } foreach (string sh in shs) { switch (sh) { case "MD2": case "MD5": case "SHA-1": case "UNKNOWN": hasBadSignHash = true; break; } } } if (hasBadSignHash) { warnings["XC001"] = "Server certificate was signed with" + " a weak/deprecated/unknown hash function."; } } /* * Print the report on the provided writer (text version for * humans). */ internal void Print(TextWriter w) { w.WriteLine("Connection: {0}:{1}", connName, connPort); if (sni == null) { w.WriteLine("No SNI sent"); } else { w.WriteLine("SNI: {0}", sni); } if (ssl2Suites != null && ssl2Suites.Length > 0) { w.WriteLine(" {0}", M.VersionString(M.SSLv20)); foreach (int s in ssl2Suites) { w.WriteLine(" {0}", CipherSuite.ToNameV2(s)); } } SupportedCipherSuites last = null; foreach (int v in suites.Keys) { w.Write(" {0}:", M.VersionString(v)); SupportedCipherSuites scs = suites[v]; if (scs.Equals(last)) { w.WriteLine(" idem"); continue; } last = scs; w.WriteLine(); w.Write(" server selection: "); if (scs.PrefClient) { w.WriteLine("uses client preferences"); } else if (scs.PrefServer) { w.WriteLine("enforce server preferences"); } else { w.WriteLine("complex"); } foreach (int s in scs.Suites) { CipherSuite cs; string strength; string fsf; string anon; string kt; if (CipherSuite.ALL.TryGetValue(s, out cs)) { strength = cs.Strength.ToString(); fsf = cs.HasForwardSecrecy ? "f" : "-"; anon = cs.IsAnonymous ? "A" : "-"; kt = cs.ServerKeyType; } else { strength = "?"; fsf = "?"; anon = "?"; kt = "?"; } w.WriteLine(" {0}{1}{2} (key: {3,4}) {4}", strength, fsf, anon, kt, CipherSuite.ToName(s)); } } w.WriteLine("========================================="); if (ssl2Chain != null) { w.WriteLine("+++++ SSLv2 certificate"); PrintCert(w, ssl2Chain, 0); } w.WriteLine("+++++ SSLv3/TLS: {0} certificate chain(s)", chains.Count); foreach (X509Chain xchain in chains.Values) { int n = xchain.Elements.Length; w.WriteLine("+++ chain: length={0}", n); if (xchain.Decodable) { w.WriteLine("names match: {0}", xchain.NamesMatch ? "yes" : "no"); w.WriteLine("includes root: {0}", xchain.IncludesRoot ? "yes" : "no"); w.Write("signature hash(es):"); foreach (string name in xchain.SignHashes) { w.Write(" {0}", name); } w.WriteLine(); } else if (n == 0) { w.WriteLine("CHAIN IS EMPTY"); } else { w.WriteLine("CHAIN PROCESSING ERROR"); } for (int i = 0; i < n; i ++) { w.WriteLine("+ certificate order: {0}", i); PrintCert(w, xchain, i); } } w.WriteLine("========================================="); w.WriteLine("Server compression support: {0}", DeflateCompress ? "yes" : "no"); if (serverTimeOffset == Int64.MinValue) { w.WriteLine("Server does not send its system time."); } else if (serverTimeOffset == Int64.MaxValue) { w.WriteLine("Server sends a random system time."); } else { DateTime dt = DateTime.UtcNow; dt = dt.AddMilliseconds((double)serverTimeOffset); w.WriteLine("Server time: {0:yyyy-MM-dd HH:mm:ss} UTC" + " (offset: {1} ms)", dt, serverTimeOffset); } w.WriteLine("Secure renegotiation support: {0}", doesRenego ? "yes" : "no"); if (minDHSize > 0) { w.WriteLine("Minimum DH size: {0}", minDHSize); } if (minECSize > 0) { w.WriteLine("Minimum EC size (no extension): {0}", minECSize); } if (minECSizeExt > 0) { w.WriteLine("Minimum EC size (with extension): {0}", minECSizeExt); if (minECSize == 0) { w.WriteLine("Server does not use EC without" + " the client extension"); } } if (namedCurves != null && namedCurves.Length > 0) { w.WriteLine("Supported curves (size and name)" + " ('*' = selected by server):"); foreach (SSLCurve nc in namedCurves) { w.WriteLine(" {0} {1,3} {2}", IsSpontaneous(nc) ? "*" : " ", nc.Size, nc.Name); } if (curveExplicitPrime > 0) { w.WriteLine(" explicit prime, size = {0}", curveExplicitPrime); } if (curveExplicitChar2 > 0) { w.WriteLine(" explicit char2, size = {0}", curveExplicitChar2); } } w.WriteLine("========================================="); if (warnings == null) { Analyse(); } if (warnings.Count == 0) { w.WriteLine("No warning."); } else { foreach (string k in warnings.Keys) { w.WriteLine("WARN[{0}]: {1}", k, warnings[k]); } } } void PrintCert(TextWriter w, X509Chain xchain, int num) { w.WriteLine("thumprint: {0}", xchain.ThumbprintsRev[num]); X509Cert xc = xchain.ElementsRev[num]; if (xc == null) { w.WriteLine("UNDECODABLE: {0}", xchain.DecodingIssuesRev[num]); } else { w.WriteLine("serial: {0}", xc.SerialHex); w.WriteLine("subject: {0}", xc.Subject.ToString()); w.WriteLine("issuer: {0}", xc.Issuer.ToString()); w.WriteLine("valid from: {0:yyyy-MM-dd HH:mm:ss} UTC", xc.ValidFrom); w.WriteLine("valid to: {0:yyyy-MM-dd HH:mm:ss} UTC", xc.ValidTo); w.WriteLine("key type: {0}", xc.KeyType); w.WriteLine("key size: {0}", xc.KeySize); string cname = xc.CurveName; if (cname != null) { w.WriteLine("key curve: {0}", cname); } w.WriteLine("sign hash: {0}", xc.HashAlgorithm); if (xc.SelfIssued) { w.WriteLine("(self-issued)"); } if (num == 0) { w.Write("server names:"); string[] names = xc.ServerNames; if (names.Length == 0) { w.WriteLine(" NONE"); } else { w.WriteLine(); foreach (string name in names) { w.WriteLine(" {0}", name); } } } } if (withPEM) { M.WritePEM(w, "CERTIFICATE", xchain.EncodedRev[num]); } } /* * Encode the report as JSON. */ internal void Print(JSON js) { js.OpenInit(false); js.AddPair("connectionName", connName); js.AddPair("connectionPort", connPort); js.AddPair("SNI", sni); if (ssl2Suites != null && ssl2Suites.Length > 0) { js.OpenPairObject("SSLv2"); js.OpenPairArray("suites"); foreach (int s in ssl2Suites) { js.OpenElementObject(); js.AddPair("id", s); js.AddPair("name", CipherSuite.ToNameV2(s)); js.Close(); } js.Close(); js.Close(); } foreach (int v in suites.Keys) { js.OpenPairObject(M.VersionString(v)); SupportedCipherSuites scs = suites[v]; string sel; if (scs.PrefClient) { sel = "client"; } else if (scs.PrefServer) { sel = "server"; } else { sel = "complex"; } js.AddPair("suiteSelection", sel); js.OpenPairArray("suites"); foreach (int s in scs.Suites) { js.OpenElementObject(); js.AddPair("id", s); js.AddPair("name", CipherSuite.ToName(s)); CipherSuite cs; if (CipherSuite.ALL.TryGetValue(s, out cs)) { js.AddPair("strength", cs.Strength); js.AddPair("forwardSecrecy", cs.HasForwardSecrecy); js.AddPair("anonymous", cs.IsAnonymous); js.AddPair("serverKeyType", cs.ServerKeyType); } js.Close(); } js.Close(); js.Close(); } if (ssl2Chain != null) { js.OpenPairObject("ssl2Cert"); PrintCert(js, ssl2Chain, 0); js.Close(); } js.OpenPairArray("ssl3Chains"); foreach (X509Chain xchain in chains.Values) { js.OpenElementObject(); int n = xchain.Elements.Length; js.AddPair("length", n); js.AddPair("decoded", xchain.Decodable); if (xchain.Decodable) { js.AddPair("namesMatch", xchain.NamesMatch); js.AddPair("includesRoot", xchain.IncludesRoot); js.OpenPairArray("signHashes"); foreach (string name in xchain.SignHashes) { js.AddElement(name); } js.Close(); } js.OpenPairArray("certificates"); for (int i = 0; i < n; i ++) { js.OpenElementObject(); PrintCert(js, xchain, i); js.Close(); } js.Close(); js.Close(); } js.Close(); js.AddPair("deflateCompress", DeflateCompress); if (serverTimeOffset == Int64.MinValue) { js.AddPair("serverTime", "none"); } else if (serverTimeOffset == Int64.MaxValue) { js.AddPair("serverTime", "random"); } else { DateTime dt = DateTime.UtcNow; dt = dt.AddMilliseconds((double)serverTimeOffset); js.AddPair("serverTime", string.Format( "{0:yyyy-MM-dd HH:mm:ss} UTC", dt)); js.AddPair("serverTimeOffsetMillis", serverTimeOffset); } js.AddPair("secureRenegotiation", doesRenego); if (minDHSize > 0) { js.AddPair("minDHSize", minDHSize); } if (minECSize > 0) { js.AddPair("minECSize", minECSize); } if (minECSizeExt > 0) { js.AddPair("minECSizeExt", minECSizeExt); } if ((namedCurves != null && namedCurves.Length > 0) || curveExplicitPrime > 0 || curveExplicitChar2 > 0) { js.OpenPairArray("namedCurves"); foreach (SSLCurve nc in namedCurves) { js.OpenElementObject(); js.AddPair("name", nc.Name); js.AddPair("size", nc.Size); js.AddPair("spontaneous", IsSpontaneous(nc)); js.Close(); } if (curveExplicitPrime > 0) { js.OpenElementObject(); js.AddPair("name", "explicitPrime"); js.AddPair("size", curveExplicitPrime); js.Close(); } if (curveExplicitChar2 > 0) { js.OpenElementObject(); js.AddPair("name", "explicitChar2"); js.AddPair("size", curveExplicitChar2); js.Close(); } js.Close(); } if (warnings == null) { Analyse(); } js.OpenPairArray("warnings"); foreach (string k in warnings.Keys) { js.OpenElementObject(); js.AddPair("id", k); js.AddPair("text", warnings[k]); js.Close(); } js.Close(); js.Close(); } /* * Add certificate to output. The caller is responsible for * opening the certificate object. */ void PrintCert(JSON js, X509Chain xchain, int num) { js.AddPair("thumbprint", xchain.ThumbprintsRev[num]); X509Cert xc = xchain.ElementsRev[num]; js.AddPair("decodable", xc != null); if (xc == null) { js.AddPair("decodeError", xchain.DecodingIssuesRev[num]); } else { js.AddPair("serialHex", xc.SerialHex); js.AddPair("subject", xc.Subject.ToString()); js.AddPair("issuer", xc.Issuer.ToString()); js.AddPair("validFrom", string.Format( "{0:yyyy-MM-dd HH:mm:ss} UTC", xc.ValidFrom)); js.AddPair("validTo", string.Format( "{0:yyyy-MM-dd HH:mm:ss} UTC", xc.ValidTo)); js.AddPair("keyType", xc.KeyType); js.AddPair("keySize", xc.KeySize); string cname = xc.CurveName; if (cname != null) { js.AddPair("keyCurve", cname); } js.AddPair("signHash", xc.HashAlgorithm); js.AddPair("selfIssued", xc.SelfIssued); if (num == 0) { js.OpenPairArray("serverNames"); foreach (string name in xc.ServerNames) { js.AddElement(name); } js.Close(); } } if (withPEM) { js.AddPair("PEM", M.ToPEM("CERTIFICATE", xchain.EncodedRev[num])); } } }
using System; using System.Collections; using NBitcoin.BouncyCastle.Asn1; using NBitcoin.BouncyCastle.Asn1.CryptoPro; using NBitcoin.BouncyCastle.Asn1.Nist; using NBitcoin.BouncyCastle.Asn1.Pkcs; using NBitcoin.BouncyCastle.Asn1.Oiw; using NBitcoin.BouncyCastle.Asn1.TeleTrust; using NBitcoin.BouncyCastle.Security; using NBitcoin.BouncyCastle.Crypto.Digests; using NBitcoin.BouncyCastle.Crypto; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Security { /// <remarks> /// Utility class for creating IDigest objects from their names/Oids /// </remarks> public sealed class DigestUtilities { private enum DigestAlgorithm { GOST3411, MD2, MD4, MD5, RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320, SHA_1, SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256, SHA3_224, SHA3_256, SHA3_384, SHA3_512, TIGER, WHIRLPOOL, }; private DigestUtilities() { } private static readonly IDictionary algorithms = Platform.CreateHashtable(); private static readonly IDictionary oids = Platform.CreateHashtable(); static DigestUtilities() { // Signal to obfuscation tools not to change enum constants ((DigestAlgorithm)Enums.GetArbitraryValue(typeof(DigestAlgorithm))).ToString(); algorithms[PkcsObjectIdentifiers.MD2.Id] = "MD2"; algorithms[PkcsObjectIdentifiers.MD4.Id] = "MD4"; algorithms[PkcsObjectIdentifiers.MD5.Id] = "MD5"; algorithms["SHA1"] = "SHA-1"; algorithms[OiwObjectIdentifiers.IdSha1.Id] = "SHA-1"; algorithms["SHA224"] = "SHA-224"; algorithms[NistObjectIdentifiers.IdSha224.Id] = "SHA-224"; algorithms["SHA256"] = "SHA-256"; algorithms[NistObjectIdentifiers.IdSha256.Id] = "SHA-256"; algorithms["SHA384"] = "SHA-384"; algorithms[NistObjectIdentifiers.IdSha384.Id] = "SHA-384"; algorithms["SHA512"] = "SHA-512"; algorithms[NistObjectIdentifiers.IdSha512.Id] = "SHA-512"; algorithms["SHA512/224"] = "SHA-512/224"; algorithms[NistObjectIdentifiers.IdSha512_224.Id] = "SHA-512/224"; algorithms["SHA512/256"] = "SHA-512/256"; algorithms[NistObjectIdentifiers.IdSha512_256.Id] = "SHA-512/256"; algorithms["RIPEMD-128"] = "RIPEMD128"; algorithms[TeleTrusTObjectIdentifiers.RipeMD128.Id] = "RIPEMD128"; algorithms["RIPEMD-160"] = "RIPEMD160"; algorithms[TeleTrusTObjectIdentifiers.RipeMD160.Id] = "RIPEMD160"; algorithms["RIPEMD-256"] = "RIPEMD256"; algorithms[TeleTrusTObjectIdentifiers.RipeMD256.Id] = "RIPEMD256"; algorithms["RIPEMD-320"] = "RIPEMD320"; // algorithms[TeleTrusTObjectIdentifiers.RipeMD320.Id] = "RIPEMD320"; algorithms[CryptoProObjectIdentifiers.GostR3411.Id] = "GOST3411"; oids["MD2"] = PkcsObjectIdentifiers.MD2; oids["MD4"] = PkcsObjectIdentifiers.MD4; oids["MD5"] = PkcsObjectIdentifiers.MD5; oids["SHA-1"] = OiwObjectIdentifiers.IdSha1; oids["SHA-224"] = NistObjectIdentifiers.IdSha224; oids["SHA-256"] = NistObjectIdentifiers.IdSha256; oids["SHA-384"] = NistObjectIdentifiers.IdSha384; oids["SHA-512"] = NistObjectIdentifiers.IdSha512; oids["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224; oids["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256; oids["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128; oids["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160; oids["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256; oids["GOST3411"] = CryptoProObjectIdentifiers.GostR3411; } /// <summary> /// Returns a ObjectIdentifier for a given digest mechanism. /// </summary> /// <param name="mechanism">A string representation of the digest meanism.</param> /// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns> public static DerObjectIdentifier GetObjectIdentifier( string mechanism) { if (mechanism == null) throw new System.ArgumentNullException("mechanism"); mechanism = Platform.ToUpperInvariant(mechanism); string aliased = (string) algorithms[mechanism]; if (aliased != null) mechanism = aliased; return (DerObjectIdentifier) oids[mechanism]; } public static ICollection Algorithms { get { return oids.Keys; } } public static IDigest GetDigest( DerObjectIdentifier id) { return GetDigest(id.Id); } public static IDigest GetDigest( string algorithm) { string upper = Platform.ToUpperInvariant(algorithm); string mechanism = (string) algorithms[upper]; if (mechanism == null) { mechanism = upper; } try { DigestAlgorithm digestAlgorithm = (DigestAlgorithm)Enums.GetEnumValue( typeof(DigestAlgorithm), mechanism); switch (digestAlgorithm) { case DigestAlgorithm.GOST3411: return new Gost3411Digest(); case DigestAlgorithm.MD2: return new MD2Digest(); case DigestAlgorithm.MD4: return new MD4Digest(); case DigestAlgorithm.MD5: return new MD5Digest(); case DigestAlgorithm.RIPEMD128: return new RipeMD128Digest(); case DigestAlgorithm.RIPEMD160: return new RipeMD160Digest(); case DigestAlgorithm.RIPEMD256: return new RipeMD256Digest(); case DigestAlgorithm.RIPEMD320: return new RipeMD320Digest(); case DigestAlgorithm.SHA_1: return new Sha1Digest(); case DigestAlgorithm.SHA_224: return new Sha224Digest(); case DigestAlgorithm.SHA_256: return new Sha256Digest(); case DigestAlgorithm.SHA_384: return new Sha384Digest(); case DigestAlgorithm.SHA_512: return new Sha512Digest(); case DigestAlgorithm.SHA_512_224: return new Sha512tDigest(224); case DigestAlgorithm.SHA_512_256: return new Sha512tDigest(256); case DigestAlgorithm.SHA3_224: return new Sha3Digest(224); case DigestAlgorithm.SHA3_256: return new Sha3Digest(256); case DigestAlgorithm.SHA3_384: return new Sha3Digest(384); case DigestAlgorithm.SHA3_512: return new Sha3Digest(512); case DigestAlgorithm.TIGER: return new TigerDigest(); case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); } } catch (ArgumentException) { } throw new SecurityUtilityException("Digest " + mechanism + " not recognised."); } public static string GetAlgorithmName( DerObjectIdentifier oid) { return (string) algorithms[oid.Id]; } public static byte[] CalculateDigest(string algorithm, byte[] input) { IDigest digest = GetDigest(algorithm); digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); } public static byte[] DoFinal( IDigest digest) { byte[] b = new byte[digest.GetDigestSize()]; digest.DoFinal(b, 0); return b; } public static byte[] DoFinal( IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); } } }
/** * JavaScriptEmitter class * Copyright(c) 2017 Steve Westbrook * MIT Licensed */ using System; using System.Reflection; using System.Globalization; using System.Linq; using System.Text; using System.Collections.Generic; using System.Collections.Concurrent; namespace EdgeGenerator { public class JavaScriptEmitter : CodeEmitter { public const string EdgeTypeName = "edge"; public const string EdgeModuleName = "edge"; public const string EdgeReferenceTypeName = "EdgeReference"; public const string EdgeReferenceModuleName = "edge-reference"; // TODO: Potentially inconsistent line endings here /** * 0 - indent * 1 - static * 2 - name * 3 - additional indent * 4 - property body */ private const string GetterTemplate = @"{0}{1}get {2}() {{ {3} {0}}}"; /** * 0 - indent * 1 - static * 2 - name * 3 - additional indent * 4 - property body */ private const string SetterTemplate = @"{0}{1}set {2}(value) {{ {3} {0}}}"; private Dictionary<string, bool> appended = new Dictionary<string, bool>(); #region .Net Wrapping public void AppendReferenceHeader() { this.buffer.AppendLine("const Reference = edge(function () { /*"); } public void AppendReferenceFooter() { this.buffer.AppendLine("*/}));"); } #endregion #region Requires /// <summary> /// Constructs and appends JavaScript require statements for the file. /// </summary> /// <param name="target">Target.</param> public void AppendBasicRequires(Type target) { AppendRequire(EdgeTypeName, EdgeModuleName); AppendRequire(EdgeReferenceTypeName, EdgeReferenceModuleName); if (target.BaseType != null && target.BaseType != typeof(object)) { AppendRelativeRequire(target.BaseType); } } public void AppendRequires(IEnumerable<Type> referenceTypes) { foreach (Type type in referenceTypes) { if (!this.appended.ContainsKey(type.Name) && ReflectionUtils.IsReferenceType(type)) { this.appended.Add(type.Name, true); this.AppendRelativeRequire(type); } } } private void AppendRequire(string name, string file) { buffer.AppendFormat ( CultureInfo.InvariantCulture, "const {0} = require('{1}');", name, file); buffer.AppendLine (); } private void AppendRelativeRequire(Type type) { string name = type.Name; this.buffer.AppendFormat( CultureInfo.InvariantCulture, "const {0} = require('./{1}.js');", name, ReflectionUtils.ConvertFullName(type.FullName ?? type.Name)); buffer.AppendLine(); } #endregion #region Class public void AppendClassDefinition(Type target) { string name = target.Name; const string ClassDefinitionTemplate = @"{0}class {1}{2} {{"; string extendsStatement = string.Empty; // If this class inherits from something, so should the proxy. // TODO: Look up type names here string baseClass = (target.BaseType != null && target.BaseType != typeof(object)) ? target.BaseType.Name : EdgeReferenceTypeName; extendsStatement = string.Concat(" extends ", baseClass); this.buffer.AppendFormat( CultureInfo.InvariantCulture, ClassDefinitionTemplate, this.CurrentIndent, name, extendsStatement); this.buffer.AppendLine(); this.buffer.AppendLine(); // Add indent for future declarations this.Indent(); } public void AppendClassTermination() { // Outdent this.Outdent(); buffer.Append(this.CurrentIndent); buffer.AppendLine("}"); } #endregion Class #region Exports public void AppendExport(Type target) { this.buffer.AppendLine(); this.buffer.Append("module.exports = "); this.buffer.AppendLine(target.Name); } #endregion #region Constructors public void AppendConstructor(ConstructorInfo source) { const string ConstructorTemplate = "{0}constructor(referenceId, args) {{"; this.buffer.AppendFormat( CultureInfo.InvariantCulture, ConstructorTemplate, this.CurrentIndent); this.BlockStart(); // TODO: allow multiple constructors with args passed in this.buffer.AppendFormat( CultureInfo.InvariantCulture, "{0}super(referenceId, Constructor, args);", this.CurrentIndent); this.buffer.AppendLine(); this.BlockEnd(); } #endregion #region Properties /// <summary> /// Generates and appends a JavaScript property to the ProxyGenerator's /// internal buffer. /// </summary> /// <param name="source"> /// Information about the property to be generated. /// </param> /// <param name="isStatic"> /// If set to <c>true</c>, the member is static. /// </param> /// <remarks> /// The property info provided could be used to determine whether the /// member is static; however a parameter is more convenient. /// </remarks> public void AppendProperty(PropertyInfo source, bool isStatic) { string baseIndent = this.CurrentIndent; string staticModifier = isStatic ? "static " : string.Empty; string getterBody = GenerateGetterBody( source.Name, source.PropertyType, isStatic); string setterBody = GenerateSetterBody( source.Name, source.PropertyType, isStatic); Action<string, string> formatAccessor = (formatString, body) => { this.buffer.AppendFormat( CultureInfo.InvariantCulture, formatString, baseIndent, staticModifier, source.Name, body); }; // used twice MethodInfo setter = source.GetSetMethod(); MethodInfo getter = source.GetGetMethod(); bool canWrite = source.CanWrite && setter != null && setter.IsPublic; // Note that public properties are defined as properties with a // public getter OR setter - therefore make sure the accessor is // public. if (source.CanRead && getter != null && getter.IsPublic) { formatAccessor(GetterTemplate, getterBody); if (canWrite) { this.AppendBreak (); } } if (canWrite) { formatAccessor(SetterTemplate, setterBody); } } private string GenerateGetterBody(string name, Type type, bool isStatic) { string result; if (ReflectionUtils.IsReferenceType(type)) { result = string.Format( CultureInfo.InvariantCulture, @"{0}{1}var returnId = Get_{2}({3}, true); {0}{1}return (returnId ? new {4}(returnId) : null);", this.CurrentIndent, this.incrementalIndent, name, isStatic ? "null" : "this._referenceId", this.DetermineJavaScriptTypeName(type)); } else { result = string.Format( CultureInfo.InvariantCulture, "{0}{1}return Get_{2}({3}, true);", this.CurrentIndent, this.incrementalIndent, name, isStatic ? "null" : "this._referenceId"); } return result; } private string GenerateSetterBody(string name, Type type, bool isStatic) { string result; if (ReflectionUtils.IsReferenceType(type)) { result = string.Format( CultureInfo.InvariantCulture, "{0}{1}Set_{2}({{ {3}value: value._referenceId }}, true);", this.CurrentIndent, this.incrementalIndent, name, isStatic ? string.Empty : "_referenceId: this._referenceId, "); } else { result = string.Format( CultureInfo.InvariantCulture, "{0}{1}Set_{2}({{ {3}value: value }}, true);", this.CurrentIndent, this.incrementalIndent, name, isStatic ? string.Empty : "_referenceId: this._referenceId, "); } return result; } #endregion Properties #region Functions public void AppendFunction(MethodInfo source, bool isStatic) { // Build argument name references ParameterInfo[] arguments = source.GetParameters(); string[] argumentNames = arguments .Select((parameter) => { return parameter.Name; }) .ToArray(); string argumentNameList = string.Join(", ", argumentNames); if (argumentNameList.Length > 0) { argumentNameList += ", "; } const string SignatureTemplate = "{0}{1}{2}({3}callback) {{"; this.buffer.AppendFormat( CultureInfo.InvariantCulture, SignatureTemplate, this.CurrentIndent, isStatic ? "static " : string.Empty, source.Name, argumentNameList); this.buffer.AppendLine(); // Indent this.Indent(); // Append argument conversions if (this.AppendArgumentConversions(source)) { this.buffer.AppendLine(); this.buffer.AppendLine(); } // Append call line this.buffer.AppendLine(GenerateFunctionCall( source, isStatic, arguments)); // Outdent this.Outdent(); this.buffer.AppendFormat ( CultureInfo.InvariantCulture, "{0}}}", this.CurrentIndent); } private bool AppendArgumentConversions(MethodInfo source) { bool result = false; foreach (ParameterInfo parameter in source.GetParameters()) { result |= AppendArgumentConversion(parameter); } return result; } private bool AppendArgumentConversion(ParameterInfo argument) { const string ArgumentConversionLineTemplate = "{0}{1} = {1} ? {1}._referenceId : 0;"; if (ReflectionUtils.IsReferenceType(argument.ParameterType)) { this.buffer.AppendFormat( CultureInfo.InvariantCulture, ArgumentConversionLineTemplate, this.CurrentIndent, argument.Name); return true; } return false; } private string GenerateFunctionCall( MethodInfo source, bool isStatic, ParameterInfo[] arguments) { const string FunctionCallLineTemplate = "{0}{1}EdgeReference.callbackOrReturn({2}{3},{2}{4},{2}{5},{2}callback);"; IEnumerable<string> argumentContent = arguments.Select(parameter => { return string.Concat( parameter.Name, ": ", parameter.Name); }); if (!isStatic) { argumentContent = (new string[] { "_referenceId: this._referenceId" }).Concat(argumentContent); } string divider = string.Concat( ",", Environment.NewLine, this.CurrentIndent, this.incrementalIndent, this.incrementalIndent ); string argumentObject; if (string.IsNullOrWhiteSpace(divider)) { argumentObject = "{}"; } else { argumentObject = string.Concat( "{", Environment.NewLine, this.CurrentIndent, this.incrementalIndent, this.incrementalIndent, string.Join(divider, argumentContent.ToArray()), Environment.NewLine, this.CurrentIndent, this.incrementalIndent, "}"); } string returnStatement; string wrapperType; if (source.ReturnType == typeof(void)) { returnStatement = string.Empty; wrapperType = "null"; } else { returnStatement = "return "; if (ReflectionUtils.IsReferenceType(source.ReturnType)) { wrapperType = source.ReturnType.Name; } else { wrapperType = "null"; } } return string.Format( CultureInfo.InvariantCulture, FunctionCallLineTemplate, this.CurrentIndent, returnStatement, Environment.NewLine + this.CurrentIndent + this.incrementalIndent, source.Name, argumentObject, wrapperType); } #endregion Functions public void AppendBreak() { this.buffer.AppendLine(); this.buffer.AppendLine(); } public void AppendLine() { this.buffer.AppendLine(); } /// <summary> /// Looks up the JavaScript type name for the specified type. /// </summary> private string DetermineJavaScriptTypeName(Type type) { // TODO: Look up set of stored names here in case of naming conflict return type.Name; } protected override void BlockStart() { this.buffer.AppendLine(); this.Indent(); } } }
/* * 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.Diagnostics; using System.Linq; using System.Threading; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Securities; using QuantConnect.Brokerages; using QuantConnect.Brokerages.GDAX; namespace QuantConnect.Tests.Brokerages { public abstract class BrokerageTests { // ideally this class would be abstract, but I wanted to keep the order test cases here which use the // various parameters required from derived types private IBrokerage _brokerage; private OrderProvider _orderProvider; private SecurityProvider _securityProvider; /// <summary> /// Provides the data required to test each order type in various cases /// </summary> public virtual TestCaseData[] OrderParameters { get { return new[] { new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"), new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"), new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"), new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder") }; } } #region Test initialization and cleanup [SetUp] public void Setup() { Log.Trace(""); Log.Trace(""); Log.Trace("--- SETUP ---"); Log.Trace(""); Log.Trace(""); // we want to regenerate these for each test _brokerage = null; _orderProvider = null; _securityProvider = null; Thread.Sleep(1000); CancelOpenOrders(); LiquidateHoldings(); Thread.Sleep(1000); } [TearDown] public void Teardown() { try { Log.Trace(""); Log.Trace(""); Log.Trace("--- TEARDOWN ---"); Log.Trace(""); Log.Trace(""); Thread.Sleep(1000); CancelOpenOrders(); LiquidateHoldings(); Thread.Sleep(1000); } finally { if (_brokerage != null) { DisposeBrokerage(_brokerage); } } } public IBrokerage Brokerage { get { if (_brokerage == null) { _brokerage = InitializeBrokerage(); } return _brokerage; } } private IBrokerage InitializeBrokerage() { Log.Trace(""); Log.Trace("- INITIALIZING BROKERAGE -"); Log.Trace(""); var brokerage = CreateBrokerage(OrderProvider, SecurityProvider); brokerage.Connect(); if (!brokerage.IsConnected) { Assert.Fail("Failed to connect to brokerage"); } //gdax does not have a user data stream. Instead, we need to symbol subscribe and monitor for our orders. if (brokerage.Name == "GDAX") { ((QuantConnect.Brokerages.GDAX.GDAXBrokerage)brokerage).Subscribe(new[] { Symbol }); } Log.Trace(""); Log.Trace("GET OPEN ORDERS"); Log.Trace(""); foreach (var openOrder in brokerage.GetOpenOrders()) { OrderProvider.Add(openOrder); } Log.Trace(""); Log.Trace("GET ACCOUNT HOLDINGS"); Log.Trace(""); foreach (var accountHolding in brokerage.GetAccountHoldings()) { // these securities don't need to be real, just used for the ISecurityProvider impl, required // by brokerages to track holdings SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol); } brokerage.OrderStatusChanged += (sender, args) => { Log.Trace(""); Log.Trace("ORDER STATUS CHANGED: " + args); Log.Trace(""); // we need to keep this maintained properly if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled) { Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString()); Security security; if (_securityProvider.TryGetValue(args.Symbol, out security)) { var holding = _securityProvider[args.Symbol].Holdings; holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity); } else { _securityProvider[args.Symbol] = CreateSecurity(args.Symbol); _securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity); } Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]); // update order mapping var order = _orderProvider.GetOrderById(args.OrderId); order.Status = args.Status; } }; return brokerage; } internal static Security CreateSecurity(Symbol symbol) { return new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)); } public OrderProvider OrderProvider { get { return _orderProvider ?? (_orderProvider = new OrderProvider()); } } public SecurityProvider SecurityProvider { get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); } } /// <summary> /// Creates the brokerage under test and connects it /// </summary> /// <returns>A connected brokerage instance</returns> protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider); /// <summary> /// Disposes of the brokerage and any external resources started in order to create it /// </summary> /// <param name="brokerage">The brokerage instance to be disposed of</param> protected virtual void DisposeBrokerage(IBrokerage brokerage) { } /// <summary> /// This is used to ensure each test starts with a clean, known state. /// </summary> protected void LiquidateHoldings() { Log.Trace(""); Log.Trace("LIQUIDATE HOLDINGS"); Log.Trace(""); var holdings = Brokerage.GetAccountHoldings(); foreach (var holding in holdings) { if (holding.Quantity == 0) continue; Log.Trace("Liquidating: " + holding); var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now); _orderProvider.Add(order); PlaceOrderWaitForStatus(order, OrderStatus.Filled); } } protected void CancelOpenOrders() { Log.Trace(""); Log.Trace("CANCEL OPEN ORDERS"); Log.Trace(""); var openOrders = Brokerage.GetOpenOrders(); foreach (var openOrder in openOrders) { Log.Trace("Canceling: " + openOrder); Brokerage.CancelOrder(openOrder); } } #endregion /// <summary> /// Gets the symbol to be traded, must be shortable /// </summary> protected abstract Symbol Symbol { get; } /// <summary> /// Gets the security type associated with the <see cref="Symbol"/> /// </summary> protected abstract SecurityType SecurityType { get; } /// <summary> /// Gets a high price for the specified symbol so a limit sell won't fill /// </summary> protected abstract decimal HighPrice { get; } /// <summary> /// Gets a low price for the specified symbol so a limit buy won't fill /// </summary> protected abstract decimal LowPrice { get; } /// <summary> /// Gets the current market price of the specified security /// </summary> protected abstract decimal GetAskPrice(Symbol symbol); /// <summary> /// Gets the default order quantity /// </summary> protected virtual decimal GetDefaultQuantity() { return 1; } [Test] public void IsConnected() { Assert.IsTrue(Brokerage.IsConnected); } [Test, TestCaseSource("OrderParameters")] public void LongFromZero(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("LONG FROM ZERO"); Log.Trace(""); PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void CloseFromLong(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("CLOSE FROM LONG"); Log.Trace(""); // first go long PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled); // now close it PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void ShortFromZero(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("SHORT FROM ZERO"); Log.Trace(""); PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void CloseFromShort(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("CLOSE FROM SHORT"); Log.Trace(""); // first go short PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled); // now close it PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void ShortFromLong(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("SHORT FROM LONG"); Log.Trace(""); // first go long PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity())); // now go net short var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus); if (parameters.ModifyUntilFilled) { ModifyOrderUntilFilled(order, parameters); } } [Test, TestCaseSource("OrderParameters")] public void LongFromShort(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("LONG FROM SHORT"); Log.Trace(""); // first fo short PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled); // now go long var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus); if (parameters.ModifyUntilFilled) { ModifyOrderUntilFilled(order, parameters); } } [Test] public void GetCashBalanceContainsUSD() { Log.Trace(""); Log.Trace("GET CASH BALANCE"); Log.Trace(""); var balance = Brokerage.GetCashBalance(); Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD")); } [Test] public void GetAccountHoldings() { Log.Trace(""); Log.Trace("GET ACCOUNT HOLDINGS"); Log.Trace(""); var before = Brokerage.GetAccountHoldings(); PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now)); var after = Brokerage.GetAccountHoldings(); var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol); var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol); var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity; var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity; Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity); } [Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerage")] public void PartialFills() { var manualResetEvent = new ManualResetEvent(false); var qty = 1000000m; var remaining = qty; var sync = new object(); Brokerage.OrderStatusChanged += (sender, orderEvent) => { lock (sync) { remaining -= orderEvent.FillQuantity; Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity); if (orderEvent.Status == OrderStatus.Filled) { manualResetEvent.Set(); } } }; // pick a security with low, but some, volume var symbol = Symbols.EURUSD; var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 }; Brokerage.PlaceOrder(order); // pause for a while to wait for fills to come in manualResetEvent.WaitOne(2500); manualResetEvent.WaitOne(2500); manualResetEvent.WaitOne(2500); Console.WriteLine("Remaining: " + remaining); Assert.AreEqual(0, remaining); } /// <summary> /// Updates the specified order in the brokerage until it fills or reaches a timeout /// </summary> /// <param name="order">The order to be modified</param> /// <param name="parameters">The order test parameters that define how to modify the order</param> /// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param> protected virtual void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90) { if (order.Status == OrderStatus.Filled) { return; } var filledResetEvent = new ManualResetEvent(false); EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) => { if (args.Status == OrderStatus.Filled) { filledResetEvent.Set(); } if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid) { Log.Trace("ModifyOrderUntilFilled(): " + order); Assert.Fail("Unexpected order status: " + args.Status); } }; Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged; Log.Trace(""); Log.Trace("MODIFY UNTIL FILLED: " + order); Log.Trace(""); var stopwatch = Stopwatch.StartNew(); while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout) { filledResetEvent.Reset(); if (order.Status == OrderStatus.PartiallyFilled) continue; var marketPrice = GetAskPrice(order.Symbol); Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice); var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice); if (updateOrder) { if (order.Status == OrderStatus.Filled) break; Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order); if (!Brokerage.UpdateOrder(order)) { Assert.Fail("Brokerage failed to update the order"); } } } Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged; } /// <summary> /// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event. /// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID. /// </summary> /// <param name="order">The order to be submitted</param> /// <param name="expectedStatus">The status to wait for</param> /// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param> /// <returns>The same order that was submitted.</returns> protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false) { var requiredStatusEvent = new ManualResetEvent(false); var desiredStatusEvent = new ManualResetEvent(false); EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) => { // no matter what, every order should fire at least one of these if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid) { Log.Trace(""); Log.Trace("SUBMITTED: " + args); Log.Trace(""); requiredStatusEvent.Set(); } // make sure we fire the status we're expecting if (args.Status == expectedStatus) { Log.Trace(""); Log.Trace("EXPECTED: " + args); Log.Trace(""); desiredStatusEvent.Set(); } }; Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged; OrderProvider.Add(order); if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission) { Assert.Fail("Brokerage failed to place the order: " + order); } requiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "Expected every order to fire a submitted or invalid status event"); desiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout. Order Id:" + order.Id); Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged; return order; } } }
// // 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.Targets { using System; using System.Collections.Generic; using System.Linq; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents logging target. /// </summary> [NLogConfigurationItem] public abstract class Target : ISupportsInitialize, IInternalLoggerContext, IDisposable { private List<Layout> _allLayouts; /// <summary> Are all layouts in this target thread-agnostic, if so we don't precalculate the layouts </summary> private bool _allLayoutsAreThreadAgnostic; private bool _allLayoutsAreThreadSafe; private bool _oneLayoutIsMutableUnsafe; private bool _scannedForLayouts; private Exception _initializeException; /// <summary> /// The Max StackTraceUsage of all the <see cref="Layout"/> in this Target /// </summary> internal StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Gets or sets the name of the target. /// </summary> /// <docgen category='General Options' order='10' /> public string Name { get; set; } /// <summary> /// Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers /// Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public bool OptimizeBufferReuse { get; set; } /// <summary> /// Gets the object which can be used to synchronize asynchronous operations that must rely on the . /// </summary> protected object SyncRoot { get; } = new object(); /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } LogFactory IInternalLoggerContext.LogFactory => LoggingConfiguration?.LogFactory; /// <summary> /// Gets a value indicating whether the target has been initialized. /// </summary> protected bool IsInitialized { get { if (_isInitialized) return true; // Initialization has completed // Lets wait for initialization to complete, and then check again lock (SyncRoot) { return _isInitialized; } } } private volatile bool _isInitialized; /// <summary> /// Can be used if <see cref="OptimizeBufferReuse"/> has been enabled. /// </summary> internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private StringBuilderPool _precalculateStringBuilderPool; /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { bool wasInitialized = _isInitialized; Initialize(configuration); if (wasInitialized && configuration != null) { FindAllLayouts(); } } } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Closes the target. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { if (asyncContinuation == null) { throw new ArgumentNullException(nameof(asyncContinuation)); } asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation); lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed asyncContinuation(null); return; } try { FlushAsync(asyncContinuation); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } asyncContinuation(exception); } } } /// <summary> /// Calls the <see cref="Layout.Precalculate"/> on each volatile layout /// used by this target. /// This method won't prerender if all layouts in this target are thread-agnostic. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> public void PrecalculateVolatileLayouts(LogEventInfo logEvent) { if (_allLayoutsAreThreadAgnostic && (!_oneLayoutIsMutableUnsafe || logEvent.IsLogEventMutableSafe())) { return; } // Not all Layouts support concurrent threads, so we have to protect them if (OptimizeBufferReuse && _allLayoutsAreThreadSafe) { PrecalculateVolatileLayoutsConcurrent(logEvent); } else { PrecalculateVolatileLayoutsWithLock(logEvent); } } private void PrecalculateVolatileLayoutsConcurrent(LogEventInfo logEvent) { if (!IsInitialized) return; if (_allLayouts == null) return; if (_precalculateStringBuilderPool == null) { System.Threading.Interlocked.CompareExchange(ref _precalculateStringBuilderPool, new StringBuilderPool(Environment.ProcessorCount * 2), null); } using (var targetBuilder = _precalculateStringBuilderPool.Acquire()) { foreach (Layout layout in _allLayouts) { targetBuilder.Item.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Item); } } } private void PrecalculateVolatileLayoutsWithLock(LogEventInfo logEvent) { lock (SyncRoot) { if (!_isInitialized) return; if (_allLayouts == null) return; if (OptimizeBufferReuse) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { foreach (Layout layout in _allLayouts) { targetBuilder.Result.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Result); } } } else { foreach (Layout layout in _allLayouts) { layout.Precalculate(logEvent); } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var targetAttribute = GetType().GetCustomAttribute<TargetAttribute>(); if (targetAttribute != null) { return $"{targetAttribute.Name} Target[{(Name ?? "(unnamed)")}]"; } return GetType().Name; } /// <summary> /// Writes the log to the target. /// </summary> /// <param name="logEvent">Log event to write.</param> public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent) { if (!IsInitialized) { lock (SyncRoot) { logEvent.Continuation(null); } return; } if (_initializeException != null) { lock (SyncRoot) { logEvent.Continuation(CreateInitException()); } return; } var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation); var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation); try { WriteAsyncThreadSafe(wrappedLogEvent); } catch (Exception ex) { if (ExceptionMustBeRethrown(ex)) throw; wrappedLogEvent.Continuation(ex); } } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents) { if (logEvents == null || logEvents.Length == 0) { return; } WriteAsyncLogEvents((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(IList<AsyncLogEventInfo> logEvents) { if (logEvents == null || logEvents.Count == 0) { return; } if (!IsInitialized) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } } return; } if (_initializeException != null) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(CreateInitException()); } } return; } IList<AsyncLogEventInfo> wrappedEvents; if (OptimizeBufferReuse) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation)); } wrappedEvents = logEvents; } else { var cloneLogEvents = new AsyncLogEventInfo[logEvents.Count]; for (int i = 0; i < logEvents.Count; ++i) { AsyncLogEventInfo ev = logEvents[i]; cloneLogEvents[i] = ev.LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(ev.Continuation)); } wrappedEvents = cloneLogEvents; } try { WriteAsyncThreadSafe(wrappedEvents); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } // in case of synchronous failure, assume that nothing is running asynchronously for (int i = 0; i < wrappedEvents.Count; ++i) { wrappedEvents[i].Continuation(exception); } } } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { LoggingConfiguration = configuration; if (!IsInitialized) { try { PropertyHelper.CheckRequiredParameters(this); InitializeTarget(); _initializeException = null; if (!_scannedForLayouts) { InternalLogger.Debug("{0}: InitializeTarget is done but not scanned For Layouts", this); //this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here. FindAllLayouts(); } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error initializing target", this); _initializeException = exception; if (ExceptionMustBeRethrown(exception)) { throw; } } finally { _isInitialized = true; } } } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { lock (SyncRoot) { LoggingConfiguration = null; if (IsInitialized) { _isInitialized = false; try { if (_initializeException == null) { // if Init succeeded, call Close() InternalLogger.Debug("Closing target '{0}'.", this); CloseTarget(); InternalLogger.Debug("Closed target '{0}'.", this); } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error closing target", this); if (ExceptionMustBeRethrown(exception)) { throw; } } } } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing && _isInitialized) { _isInitialized = false; if (_initializeException == null) { CloseTarget(); } } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected virtual void InitializeTarget() { //rescan as amount layouts can be changed. FindAllLayouts(); } private void FindAllLayouts() { _allLayouts = ObjectGraphScanner.FindReachableObjects<Layout>(false, this); InternalLogger.Trace("{0} has {1} layouts", this, _allLayouts.Count); _allLayoutsAreThreadAgnostic = _allLayouts.All(layout => layout.ThreadAgnostic); _oneLayoutIsMutableUnsafe = _allLayoutsAreThreadAgnostic && _allLayouts.Any(layout => layout.MutableUnsafe); if (!_allLayoutsAreThreadAgnostic || _oneLayoutIsMutableUnsafe) { _allLayoutsAreThreadSafe = _allLayouts.All(layout => layout.ThreadSafe); } StackTraceUsage = _allLayouts.DefaultIfEmpty().Max(layout => layout?.StackTraceUsage ?? StackTraceUsage.None); if (this is IUsesStackTrace usesStackTrace && usesStackTrace.StackTraceUsage > StackTraceUsage) StackTraceUsage = usesStackTrace.StackTraceUsage; _scannedForLayouts = true; } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected virtual void CloseTarget() { } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected virtual void FlushAsync(AsyncContinuation asyncContinuation) { asyncContinuation(null); } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected virtual void Write(LogEventInfo logEvent) { // Override to perform the actual write-operation } /// <summary> /// Writes async log event to the log target. /// </summary> /// <param name="logEvent">Async Log event to be written out.</param> protected virtual void Write(AsyncLogEventInfo logEvent) { try { Write(logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } logEvent.Continuation(exception); } } /// <summary> /// Writes a log event to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// thread-safe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvent">Log event to be written out.</param> protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed logEvent.Continuation(null); return; } Write(logEvent); } } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void Write(IList<AsyncLogEventInfo> logEvents) { for (int i = 0; i < logEvents.Count; ++i) { Write(logEvents[i]); } } /// <summary> /// NOTE! Obsolete, instead override WriteAsyncThreadSafe(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target, in a thread safe manner. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// thread-safe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo[] logEvents) { WriteAsyncThreadSafe((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// thread-safe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } return; } if (!OptimizeBufferReuse && logEvents is AsyncLogEventInfo[] logEventsArray) { // Backwards compatibility #pragma warning disable 612, 618 Write(logEventsArray); #pragma warning restore 612, 618 } else { Write(logEvents); } } } private Exception CreateInitException() { return new NLogRuntimeException($"Target {this} failed to initialize.", _initializeException); } /// <summary> /// Merges (copies) the event context properties from any event info object stored in /// parameters of the given event info object. /// </summary> /// <param name="logEvent">The event info object to perform the merge to.</param> [Obsolete("Logger.Trace(logEvent) now automatically captures the logEvent Properties. Marked obsolete on NLog 4.6")] protected void MergeEventProperties(LogEventInfo logEvent) { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { return; } //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 < logEvent.Parameters.Length; ++i) { if (logEvent.Parameters[i] is LogEventInfo logEventParameter && logEventParameter.HasProperties) { foreach (var key in logEventParameter.Properties.Keys) { logEvent.Properties.Add(key, logEventParameter.Properties[key]); } logEventParameter.Properties.Clear(); } } } /// <summary> /// Renders the event info in layout. /// </summary> /// <param name="layout">The layout.</param> /// <param name="logEvent">The event info.</param> /// <returns>String representing log event.</returns> protected string RenderLogEvent(Layout layout, LogEventInfo logEvent) { if (layout == null || logEvent == null) return null; // Signal that input was wrong if (OptimizeBufferReuse) { SimpleLayout simpleLayout = layout as SimpleLayout; if (simpleLayout != null && simpleLayout.IsFixedText) { return simpleLayout.Render(logEvent); } if (TryGetCachedValue(layout, logEvent, out var value)) { return value; } if (simpleLayout != null && simpleLayout.IsSimpleStringText) { return simpleLayout.Render(logEvent); } using (var localTarget = ReusableLayoutBuilder.Allocate()) { return layout.RenderAllocateBuilder(logEvent, localTarget.Result); } } else { return layout.Render(logEvent); } } private static bool TryGetCachedValue(Layout layout, LogEventInfo logEvent, out string value) { if ((!layout.ThreadAgnostic || layout.MutableUnsafe) && logEvent.TryGetCachedLayoutValue(layout, out var value2)) { value = value2?.ToString() ?? string.Empty; return true; } value = null; return false; } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Target.</typeparam> /// <param name="name"> Name of the Target.</param> public static void Register<T>(string name) where T : Target { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="targetType"> Type of the Target.</param> /// <param name="name"> Name of the Target.</param> public static void Register(string name, Type targetType) { ConfigurationItemFactory.Default.Targets .RegisterDefinition(name, targetType); } /// <summary> /// Should the exception be rethrown? /// </summary> /// <param name="exception"></param> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> internal bool ExceptionMustBeRethrown(Exception exception) { return exception.MustBeRethrown(this); } } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Globalization; using System.Text; using System.IO; using System.Security; namespace MiniXml { internal class MiniXmlParser { public interface IXmlHandler { void OnStartParsing(MiniXmlParser parser); void OnEndParsing(MiniXmlParser parser); void OnStart(string szName, IAttributeList attrsList); void OnEnd(string szName); void OnProcess(string szName, string content); void OnChars(string content); void OnIgnorableSpaces(string content); } public interface IAttributeList { int AttrLength { get; } bool IsEmpty { get; } string GetAttrName(int i); string GetAttrValue(int i); string GetAttrValue(string name); string[] Names { get; } string[] Values { get; } } private class AttributeListImpl : IAttributeList { public int AttrLength { get { return attrNames.Count; } } public bool IsEmpty { get { return attrNames.Count == 0; } } public string GetAttrName(int i) { return (string)attrNames[i]; } public string GetAttrValue(int i) { return (string)attrValues[i]; } public string GetAttrValue(string name) { for (int i = 0; i < attrNames.Count; i++) if ((string)attrNames[i] == name) { return (string)attrValues[i]; } return null; } public string[] Names { get { return (string[])attrNames.ToArray(typeof(string)); } } public string[] Values { get { return (string[])attrValues.ToArray(typeof(string)); } } private ArrayList attrNames = new ArrayList(); private ArrayList attrValues = new ArrayList(); internal void Clear() { attrNames.Clear(); attrValues.Clear(); } internal void Add(string name, string value) { attrNames.Add(name); attrValues.Add(value); } } private IXmlHandler xmlHandler_; private TextReader textReader_; private Stack elementNames_ = new Stack(); private Stack xmlSpaces_ = new Stack(); private string xmlBlank_; private StringBuilder stringBuffer_ = new StringBuilder(200); private char[] nameBufferArray_ = new char[30]; private bool isBlank_; private AttributeListImpl _attributes = new AttributeListImpl(); private int line = 1, column; private bool resetCol_; public MiniXmlParser() { } private static bool IsUnicodeSep(char c, bool start) { switch (Char.GetUnicodeCategory(c)) { case UnicodeCategory.LowercaseLetter: case UnicodeCategory.UppercaseLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.LetterNumber: return true; case UnicodeCategory.SpacingCombiningMark: case UnicodeCategory.EnclosingMark: case UnicodeCategory.NonSpacingMark: case UnicodeCategory.ModifierLetter: case UnicodeCategory.DecimalDigitNumber: return !start; default: return false; } } private Exception ErrorMsg_(string msg) { return new MiniXmlParserException(msg, line, column); } private Exception UnexpectedEndException_() { string[] arr = new string[elementNames_.Count]; (elementNames_ as ICollection).CopyTo(arr, 0); return ErrorMsg_(String.Format( "Unexpected end of stream. Element stack content is {0}", String.Join(",", arr))); } private bool IsNameChararcter_(char c, bool start) { switch (c) { case ':': case '_': return true; case '-': case '.': return !start; } if (c > 0x100) { switch (c) { case '\u0559': case '\u06E5': case '\u06E6': return true; } if ('\u02BB' <= c && c <= '\u02C1') { return true; } } return IsUnicodeSep(c, start); } private bool IsBlank_(int c) { switch (c) { case ' ': case '\r': case '\t': case '\n': return true; default: return false; } } public void SkipBlank() { SkipBlanks_(false); } public void SkipBlanks_(bool expected) { while (true) { switch (PeekNext_()) { case ' ': case '\r': case '\t': case '\n': ReadNext_(); if (expected) { expected = false; } continue; } if (expected) { throw ErrorMsg_("Whitespace is expected."); } return; } } private void HandleBlank_() { while (IsBlank_(PeekNext_())) { stringBuffer_.Append((char)ReadNext_()); } if (PeekNext_() != '<' && PeekNext_() >= 0) { isBlank_ = false; } } private int ReadNext_() { int i = textReader_.Read(); if (i == '\n') { resetCol_ = true; } if (resetCol_) { line++; resetCol_ = false; column = 1; } else { column++; } return i; } private int PeekNext_() { return textReader_.Peek(); } public void Expect(int c) { int p = ReadNext_(); if (p < 0) { throw UnexpectedEndException_(); } else if (p != c) { throw ErrorMsg_(String.Format("Expected '{0}' but got {1}", (char)c, (char)p)); } } public string ReadName() { int idx = 0; if (PeekNext_() < 0 || !IsNameChararcter_((char)PeekNext_(), true)) { throw ErrorMsg_("XML name start character is expected."); } for (int i = PeekNext_(); i >= 0; i = PeekNext_()) { char c = (char)i; if (!IsNameChararcter_(c, false)) { break; } if (idx == nameBufferArray_.Length) { char[] tmp = new char[idx * 2]; Array.Copy(nameBufferArray_, 0, tmp, 0, idx); nameBufferArray_ = tmp; } nameBufferArray_[idx++] = c; ReadNext_(); } if (idx == 0) { throw ErrorMsg_("Valid XML name is expected."); } return new string(nameBufferArray_, 0, idx); } public void Parse(TextReader input, IXmlHandler handler) { this.textReader_ = input; this.xmlHandler_ = handler; handler.OnStartParsing(this); while (PeekNext_() >= 0) { ReadAll(); } HandleBufferContent_(); if (elementNames_.Count > 0) { throw ErrorMsg_(String.Format("Insufficient close tag: {0}", elementNames_.Peek())); } handler.OnEndParsing(this); Cleanup(); } private string ReadUntil_(char until, bool handleReferences) { while (true) { if (PeekNext_() < 0) { throw UnexpectedEndException_(); } char c = (char)ReadNext_(); if (c == until) { break; } else if (handleReferences && c == '&') { ReadRef_(); } else { stringBuffer_.Append(c); } } string ret = stringBuffer_.ToString(); stringBuffer_.Length = 0; return ret; } private void Cleanup() { line = 1; column = 0; xmlHandler_ = null; textReader_ = null; elementNames_.Clear(); xmlSpaces_.Clear(); _attributes.Clear(); stringBuffer_.Length = 0; xmlBlank_ = null; isBlank_ = false; } public void ReadAll() { string name; if (IsBlank_(PeekNext_())) { if (stringBuffer_.Length == 0) { isBlank_ = true; } HandleBlank_(); } if (PeekNext_() == '<') { ReadNext_(); switch (PeekNext_()) { case '!': ReadNext_(); if (PeekNext_() == '[') { ReadNext_(); if (ReadName() != "CDATA") { throw ErrorMsg_("Invalid declaration markup"); } Expect('['); ReadCDATA_(); return; } else if (PeekNext_() == '-') { ReadComment_(); return; } else if (ReadName() != "DOCTYPE") { throw ErrorMsg_("Invalid declaration markup."); } else { throw ErrorMsg_("This parser does not support document type."); } case '?': HandleBufferContent_(); ReadNext_(); name = ReadName(); SkipBlank(); string text = String.Empty; if (PeekNext_() != '?') { while (true) { text += ReadUntil_('?', false); if (PeekNext_() == '>') { break; } text += "?"; } } xmlHandler_.OnProcess( name, text); Expect('>'); return; case '/': HandleBufferContent_(); if (elementNames_.Count == 0) { throw UnexpectedEndException_(); } ReadNext_(); name = ReadName(); SkipBlank(); string expected = (string)elementNames_.Pop(); xmlSpaces_.Pop(); if (xmlSpaces_.Count > 0) { xmlBlank_ = (string)xmlSpaces_.Peek(); } else { xmlBlank_ = null; } if (name != expected) { throw ErrorMsg_(String.Format("End tag mismatch: expected {0} but found {1}", expected, name)); } xmlHandler_.OnEnd(name); Expect('>'); return; default: HandleBufferContent_(); name = ReadName(); while (PeekNext_() != '>' && PeekNext_() != '/') { ReadAttr_(_attributes); } xmlHandler_.OnStart(name, _attributes); _attributes.Clear(); SkipBlank(); if (PeekNext_() == '/') { ReadNext_(); xmlHandler_.OnEnd(name); } else { elementNames_.Push(name); xmlSpaces_.Push(xmlBlank_); } Expect('>'); return; } } else { ReadChars_(); } } private void ReadChars_() { isBlank_ = false; while (true) { int i = PeekNext_(); switch (i) { case -1: return; case '<': return; case '&': ReadNext_(); ReadRef_(); continue; default: stringBuffer_.Append((char)ReadNext_()); continue; } } } private void ReadRef_() { if (PeekNext_() == '#') { ReadNext_(); ReadCharRef_(); } else { string name = ReadName(); Expect(';'); switch (name) { case "amp": stringBuffer_.Append('&'); break; case "quot": stringBuffer_.Append('"'); break; case "apos": stringBuffer_.Append('\''); break; case "lt": stringBuffer_.Append('<'); break; case "gt": stringBuffer_.Append('>'); break; default: throw ErrorMsg_("General non-predefined entity reference is not supported in this parser."); } } } private void HandleBufferContent_() { if (stringBuffer_.Length == 0) { return; } if (isBlank_) { xmlHandler_.OnIgnorableSpaces(stringBuffer_.ToString()); } else { xmlHandler_.OnChars(stringBuffer_.ToString()); } stringBuffer_.Length = 0; isBlank_ = false; } private int ReadCharRef_() { int n = 0; if (PeekNext_() == 'x') { ReadNext_(); for (int i = PeekNext_(); i >= 0; i = PeekNext_()) { if ('0' <= i && i <= '9') { n = n << 4 + i - '0'; } else if ('A' <= i && i <= 'F') { n = n << 4 + i - 'A' + 10; } else if ('a' <= i && i <= 'f') { n = n << 4 + i - 'a' + 10; } else { break; } ReadNext_(); } } else { for (int i = PeekNext_(); i >= 0; i = PeekNext_()) { if ('0' <= i && i <= '9') { n = n << 4 + i - '0'; } else { break; } ReadNext_(); } } return n; } private void ReadAttr_(AttributeListImpl a) { SkipBlanks_(true); if (PeekNext_() == '/' || PeekNext_() == '>') { return; } string name = ReadName(); string value; SkipBlank(); Expect('='); SkipBlank(); switch (ReadNext_()) { case '\'': value = ReadUntil_('\'', true); break; case '"': value = ReadUntil_('"', true); break; default: throw ErrorMsg_("Invalid attribute value markup."); } if (name == "xml:space") { xmlBlank_ = value; } a.Add(name, value); } private void ReadComment_() { Expect('-'); Expect('-'); while (true) { if (ReadNext_() != '-') { continue; } if (ReadNext_() != '-') { continue; } if (ReadNext_() != '>') { throw ErrorMsg_("'--' is not allowed inside comment markup."); } break; } } private void ReadCDATA_() { int nBracket = 0; while (true) { if (PeekNext_() < 0) { throw UnexpectedEndException_(); } char c = (char)ReadNext_(); if (c == ']') { nBracket++; } else if (c == '>' && nBracket > 1) { for (int i = nBracket; i > 2; i--) { stringBuffer_.Append(']'); } break; } else { for (int i = 0; i < nBracket; i++) { stringBuffer_.Append(']'); } nBracket = 0; stringBuffer_.Append(c); } } } } internal class SecurityParser : MiniXmlParser, MiniXmlParser.IXmlHandler { private SecurityElement root; public SecurityParser() : base() { stack = new Stack(); } public void LoadXml(string xml) { root = null; stack.Clear(); Parse(new StringReader(xml), this); } public SecurityElement ToXml() { return root; } private SecurityElement current; private Stack stack; public void OnStartParsing(MiniXmlParser parser) { } public void OnProcess(string name, string text) { } public void OnIgnorableSpaces(string s) { } public void OnStart(string name, MiniXmlParser.IAttributeList attrs) { SecurityElement newel = new SecurityElement(name); if (root == null) { root = newel; current = newel; } else { SecurityElement parent = (SecurityElement)stack.Peek(); parent.AddChild(newel); } stack.Push(newel); current = newel; int n = attrs.AttrLength; for (int i = 0; i < n; i++) { string attrName = SecurityElement.Escape(attrs.GetAttrName(i)); string attrValue = SecurityElement.Escape(attrs.GetAttrValue(i)); current.AddAttribute(attrName, attrValue); } } public void OnEnd(string name) { current = (SecurityElement)stack.Pop(); } public void OnChars(string ch) { current.Text = ch; } public void OnEndParsing(MiniXmlParser parser) { } } internal class MiniXmlParserException : SystemException { private int line; private int column; public MiniXmlParserException(string msg, int line, int column) : base(String.Format("{0}. At ({1},{2})", msg, line, column)) { this.line = line; this.column = column; } public int Line { get { return line; } } public int Column { get { return column; } } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IEqualityComparer<T>.GetHashCode(T) /// </summary> public class IEqualityComparerGetHashCode { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { IEqualityComparerGetHashCode testObj = new IEqualityComparerGetHashCode(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.IEqualityComparer<T>.GetHashCode(T"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using EqualityComparer<T> which implemented the GetHashCode method in IEqualityComparer<T> and Type is int..."; const string c_TEST_ID = "P001"; EqualityComparer<int> equalityComparer = EqualityComparer<int>.Default; int x = TestLibrary.Generator.GetInt32(-55); int expectedValue = x.GetHashCode(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int actualValue = ((IEqualityComparer<int>)equalityComparer).GetHashCode(x); if (expectedValue != actualValue) { string errorDesc = "Value is not " + actualValue + " as expected: Actual(" + expectedValue + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using EqualityComparer<T> which implemented the GetHashCode method in IEqualityComparer<T> and Type is string..."; const string c_TEST_ID = "P002"; EqualityComparer<String> equalityComparer = EqualityComparer<String>.Default; string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); int expectedValue = str.GetHashCode(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int actualValue = ((IEqualityComparer<String>)equalityComparer).GetHashCode(str); if (expectedValue != actualValue) { string errorDesc = "Value is not " + actualValue + " as expected: Actual(" + expectedValue + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using EqualityComparer<T> which implemented the GetHashCode method in IEqualityComparer<T> and Type is user-defined class..."; const string c_TEST_ID = "P003"; EqualityComparer<MyClass> equalityComparer = EqualityComparer<MyClass>.Default; MyClass myclass1 = new MyClass(); int expectedValue = myclass1.GetHashCode(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int actualValue = ((IEqualityComparer<MyClass>)equalityComparer).GetHashCode(myclass1); if (expectedValue != actualValue) { string errorDesc = "Value is not " + actualValue + " as expected: Actual(" + expectedValue + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using user-defined class which implemented the GetHashCode method in IEqualityComparer<T>..."; const string c_TEST_ID = "P004"; MyEqualityComparer<String> myEC = new MyEqualityComparer<String>(); String str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); int expectedValue = str.GetHashCode(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int actualValue = ((IEqualityComparer<String>)myEC).GetHashCode(str); if (expectedValue != actualValue) { string errorDesc = "Value is not " + actualValue + " as expected: Actual(" + expectedValue + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Negative tests public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: object is a null reference"; const string c_TEST_ID = "N001"; MyEqualityComparer<MyClass> myEC = new MyEqualityComparer<MyClass>(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IEqualityComparer<MyClass>)myEC).GetHashCode(null); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyEqualityComparer<T> : IEqualityComparer<T> { #region IEqualityComparer<T> Members bool IEqualityComparer<T>.Equals(T x, T y) { throw new Exception("The method or operation is not implemented."); } int IEqualityComparer<T>.GetHashCode(T obj) { if (obj == null) throw new ArgumentNullException(); return obj.GetHashCode(); } #endregion } public class MyClass { } #endregion }
using System; using log4net; namespace SqlServerCacheClient.Logging { internal class Log4NetWrapper : ILogger { private static bool configured = false; private static void ConfigureLog4Net() { if (!configured) { log4net.Config.XmlConfigurator.Configure(); configured = true; } } private readonly ILog iLog; public Log4NetWrapper(Type type) { ConfigureLog4Net(); this.iLog = log4net.LogManager.GetLogger(type); } public void SetVerbosity(LoggingVerbosity verbosity) { switch (verbosity) { case LoggingVerbosity.Debug : ((log4net.Repository.Hierarchy.Logger)iLog.Logger).Level = log4net.Core.Level.Debug; break; case LoggingVerbosity.Info: ((log4net.Repository.Hierarchy.Logger)iLog.Logger).Level = log4net.Core.Level.Info; break; case LoggingVerbosity.Warn: ((log4net.Repository.Hierarchy.Logger) iLog.Logger).Level = log4net.Core.Level.Warn; break; case LoggingVerbosity.Error: ((log4net.Repository.Hierarchy.Logger) iLog.Logger).Level = log4net.Core.Level.Error; break; case LoggingVerbosity.Fatal: ((log4net.Repository.Hierarchy.Logger) iLog.Logger).Level = log4net.Core.Level.Fatal; break; } } public bool IsDebugEnabled { get { return iLog.IsDebugEnabled; } } public bool IsErrorEnabled { get { return iLog.IsErrorEnabled; } } public bool IsFatalEnabled { get { return iLog.IsFatalEnabled; } } public bool IsInfoEnabled { get { return iLog.IsInfoEnabled; } } public bool IsWarnEnabled { get { return iLog.IsWarnEnabled; } } public void Debug(object message) { iLog.Debug(message); } public void Debug(object message, Exception exception) { iLog.Debug(message, exception); } public void DebugFormat(string format, object arg0) { iLog.DebugFormat(format, arg0); } public void DebugFormat(string format, params object[] args) { iLog.DebugFormat(format, args); } public void DebugFormat(string format, object arg0, object arg1) { iLog.DebugFormat(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { iLog.DebugFormat(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { iLog.DebugFormat(provider, format, args); } public void Info(object message) { iLog.Info(message); } public void Info(object message, Exception exception) { iLog.Info(message, exception); } public void InfoFormat(string format, params object[] args) { iLog.InfoFormat(format, args); } public void InfoFormat(string format, object arg0) { iLog.InfoFormat(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { iLog.InfoFormat(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { iLog.InfoFormat(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { iLog.InfoFormat(provider, format, args); } public void Warn(object message) { iLog.Warn(message); } public void Warn(object message, Exception exception) { iLog.Warn(message, exception); } public void WarnFormat(string format, params object[] args) { iLog.WarnFormat(format, args); } public void WarnFormat(string format, object arg0) { iLog.WarnFormat(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { iLog.WarnFormat(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { iLog.WarnFormat(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { iLog.WarnFormat(provider, format, args); } public void Error(object message) { iLog.Error(message); } public void Error(object message, Exception exception) { iLog.Error(message, exception); } public void ErrorFormat(string format, params object[] args) { iLog.ErrorFormat(format, args); } public void ErrorFormat(string format, object arg0) { iLog.ErrorFormat(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { iLog.ErrorFormat(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { iLog.ErrorFormat(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { iLog.ErrorFormat(provider, format, args); } public void Fatal(object message) { iLog.Fatal(message); } public void Fatal(object message, Exception exception) { iLog.Fatal(message, exception); } public void FatalFormat(string format, params object[] args) { iLog.FatalFormat(format, args); } public void FatalFormat(string format, object arg0) { iLog.FatalFormat(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { iLog.FatalFormat(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { iLog.FatalFormat(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { iLog.FatalFormat(provider, format, args); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System { internal static class IriHelper { // // Checks if provided non surrogate char lies in iri range // internal static bool CheckIriUnicodeRange(char unicode, bool isQuery) { return ((unicode >= '\u00A0' && unicode <= '\uD7FF') || (unicode >= '\uF900' && unicode <= '\uFDCF') || (unicode >= '\uFDF0' && unicode <= '\uFFEF') || (isQuery && unicode >= '\uE000' && unicode <= '\uF8FF')); } // // Check if highSurr and lowSurr are a surrogate pair then // it checks if the combined char is in the range // Takes in isQuery because because iri restrictions for query are different // internal static bool CheckIriUnicodeRange(char highSurr, char lowSurr, ref bool surrogatePair, bool isQuery) { bool inRange = false; surrogatePair = false; Debug.Assert(char.IsHighSurrogate(highSurr)); if (char.IsSurrogatePair(highSurr, lowSurr)) { surrogatePair = true; char[] chars = new char[2] { highSurr, lowSurr }; string surrPair = new string(chars); if (((string.CompareOrdinal(surrPair, "\U00010000") >= 0) && (string.CompareOrdinal(surrPair, "\U0001FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00020000") >= 0) && (string.CompareOrdinal(surrPair, "\U0002FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00030000") >= 0) && (string.CompareOrdinal(surrPair, "\U0003FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00040000") >= 0) && (string.CompareOrdinal(surrPair, "\U0004FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00050000") >= 0) && (string.CompareOrdinal(surrPair, "\U0005FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00060000") >= 0) && (string.CompareOrdinal(surrPair, "\U0006FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00070000") >= 0) && (string.CompareOrdinal(surrPair, "\U0007FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00080000") >= 0) && (string.CompareOrdinal(surrPair, "\U0008FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00090000") >= 0) && (string.CompareOrdinal(surrPair, "\U0009FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000A0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000AFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000B0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000BFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000C0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000CFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000D0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000DFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000E1000") >= 0) && (string.CompareOrdinal(surrPair, "\U000EFFFD") <= 0)) || (isQuery && (((string.CompareOrdinal(surrPair, "\U000F0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000FFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00100000") >= 0) && (string.CompareOrdinal(surrPair, "\U0010FFFD") <= 0))))) { inRange = true; } } return inRange; } // // Check reserved chars according to rfc 3987 in a sepecific component // internal static bool CheckIsReserved(char ch, UriComponents component) { if ((component != UriComponents.Scheme) && (component != UriComponents.UserInfo) && (component != UriComponents.Host) && (component != UriComponents.Port) && (component != UriComponents.Path) && (component != UriComponents.Query) && (component != UriComponents.Fragment) ) { return (component == (UriComponents)0) ? Uri.IsGenDelim(ch) : false; } else { switch (component) { // Reserved chars according to rfc 3987 case UriComponents.UserInfo: if (ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@') return true; break; case UriComponents.Host: if (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@') return true; break; case UriComponents.Path: if (ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']') return true; break; case UriComponents.Query: if (ch == '#' || ch == '[' || ch == ']') return true; break; case UriComponents.Fragment: if (ch == '#' || ch == '[' || ch == ']') return true; break; default: break; } return false; } } // // IRI normalization for strings containing characters that are not allowed or // escaped characters that should be unescaped in the context of the specified Uri component. // internal static unsafe string EscapeUnescapeIri(char* pInput, int start, int end, UriComponents component) { char[] dest = new char[end - start]; byte[] bytes = null; // Pin the array to do pointer accesses GCHandle destHandle = GCHandle.Alloc(dest, GCHandleType.Pinned); char* pDest = (char*)destHandle.AddrOfPinnedObject(); const int percentEncodingLen = 3; // Escaped UTF-8 will take 3 chars: %AB. const int bufferCapacityIncrease = 30 * percentEncodingLen; int bufferRemaining = 0; int next = start; int destOffset = 0; char ch; bool escape = false; bool surrogatePair = false; for (; next < end; ++next) { escape = false; surrogatePair = false; if ((ch = pInput[next]) == '%') { if (next + 2 < end) { ch = UriHelper.EscapedAscii(pInput[next + 1], pInput[next + 2]); // Do not unescape a reserved char if (ch == Uri.c_DummyChar || ch == '%' || CheckIsReserved(ch, component) || UriHelper.IsNotSafeForUnescape(ch)) { // keep as is Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; continue; } else if (ch <= '\x7F') { Debug.Assert(ch < 0xFF, "Expecting ASCII character."); Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); //ASCII pDest[destOffset++] = ch; next += 2; continue; } else { // possibly utf8 encoded sequence of unicode // check if safe to unescape according to Iri rules Debug.Assert(ch < 0xFF, "Expecting ASCII character."); int startSeq = next; int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pInput[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = UriHelper.EscapedAscii(pInput[next + 1], pInput[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } Debug.Assert(ch < 0xFF, "Expecting ASCII character."); } next--; // for loop will increment // Using encoder with no replacement fall-back will skip all invalid UTF-8 sequences. Encoding noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); char[] unescapedChars = new char[bytes.Length]; int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); if (charCount != 0) { // If invalid sequences were present in the original escaped string, we need to // copy the escaped versions of those sequences. // Decoded Unicode values will be kept only when they are allowed by the URI/IRI RFC // rules. UriHelper.MatchUTF8Sequence(pDest, dest, ref destOffset, unescapedChars, charCount, bytes, byteCount, component == UriComponents.Query, true); } else { // copy escaped sequence as is for (int i = startSeq; i <= next; ++i) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[i]; } } } } else { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else if (ch > '\x7f') { // unicode char ch2; if ((char.IsHighSurrogate(ch)) && (next + 1 < end)) { ch2 = pInput[next + 1]; escape = !CheckIriUnicodeRange(ch, ch2, ref surrogatePair, component == UriComponents.Query); if (!escape) { // copy the two chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else { if (CheckIriUnicodeRange(ch, component == UriComponents.Query)) { if (!Uri.IsBidiControlCharacter(ch)) { // copy it Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else { // escape it escape = true; } } } else { // just copy the character Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } if (escape) { const int maxNumberOfBytesEncoded = 4; if (bufferRemaining < maxNumberOfBytesEncoded * percentEncodingLen) { int newBufferLength = 0; checked { // may need more memory since we didn't anticipate escaping newBufferLength = dest.Length + bufferCapacityIncrease; bufferRemaining += bufferCapacityIncrease; } char[] newDest = new char[newBufferLength]; fixed (char* pNewDest = newDest) { Buffer.MemoryCopy((byte*)pDest, (byte*)pNewDest, newBufferLength, destOffset * sizeof(char)); } if (destHandle.IsAllocated) { destHandle.Free(); } dest = newDest; // re-pin new dest[] array destHandle = GCHandle.Alloc(dest, GCHandleType.Pinned); pDest = (char*)destHandle.AddrOfPinnedObject(); } byte[] encodedBytes = new byte[maxNumberOfBytesEncoded]; fixed (byte* pEncodedBytes = encodedBytes) { int encodedBytesCount = Encoding.UTF8.GetBytes(pInput + next, surrogatePair ? 2 : 1, pEncodedBytes, maxNumberOfBytesEncoded); Debug.Assert(encodedBytesCount <= maxNumberOfBytesEncoded, "UTF8 encoder should not exceed specified byteCount"); bufferRemaining -= encodedBytesCount * percentEncodingLen; for (int count = 0; count < encodedBytesCount; ++count) { UriHelper.EscapeAsciiChar((char)encodedBytes[count], dest, ref destOffset); } } } } if (destHandle.IsAllocated) destHandle.Free(); Debug.Assert(destOffset <= dest.Length, "Destination length met or exceeded destination offset."); return new string(dest, 0, destOffset); } } }
using System; namespace YAF.Lucene.Net.Search.Similarities { /* * 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 AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FieldInvertState = YAF.Lucene.Net.Index.FieldInvertState; using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues; using SmallSingle = YAF.Lucene.Net.Util.SmallSingle; /// <summary> /// BM25 Similarity. Introduced in Stephen E. Robertson, Steve Walker, /// Susan Jones, Micheline Hancock-Beaulieu, and Mike Gatford. Okapi at TREC-3. /// In Proceedings of the Third <b>T</b>ext <b>RE</b>trieval <b>C</b>onference (TREC 1994). /// Gaithersburg, USA, November 1994. /// <para/> /// @lucene.experimental /// </summary> public class BM25Similarity : Similarity { private readonly float k1; private readonly float b; // TODO: should we add a delta like sifaka.cs.uiuc.edu/~ylv2/pub/sigir11-bm25l.pdf ? /// <summary> /// BM25 with the supplied parameter values. </summary> /// <param name="k1"> Controls non-linear term frequency normalization (saturation). </param> /// <param name="b"> Controls to what degree document length normalizes tf values. </param> public BM25Similarity(float k1, float b) { this.k1 = k1; this.b = b; } /// <summary> /// BM25 with these default values: /// <list type="bullet"> /// <item><description><c>k1 = 1.2</c>,</description></item> /// <item><description><c>b = 0.75</c>.</description></item> /// </list> /// </summary> public BM25Similarity() { this.k1 = 1.2f; this.b = 0.75f; } /// <summary> /// Implemented as <c>log(1 + (numDocs - docFreq + 0.5)/(docFreq + 0.5))</c>. </summary> protected internal virtual float Idf(long docFreq, long numDocs) { return (float)Math.Log(1 + (numDocs - docFreq + 0.5D) / (docFreq + 0.5D)); } /// <summary> /// Implemented as <c>1 / (distance + 1)</c>. </summary> protected internal virtual float SloppyFreq(int distance) { return 1.0f / (distance + 1); } /// <summary> /// The default implementation returns <c>1</c> </summary> protected internal virtual float ScorePayload(int doc, int start, int end, BytesRef payload) { return 1; } /// <summary> /// The default implementation computes the average as <c>sumTotalTermFreq / maxDoc</c>, /// or returns <c>1</c> if the index does not store sumTotalTermFreq (Lucene 3.x indexes /// or any field that omits frequency information). /// </summary> protected internal virtual float AvgFieldLength(CollectionStatistics collectionStats) { long sumTotalTermFreq = collectionStats.SumTotalTermFreq; if (sumTotalTermFreq <= 0) { return 1f; // field does not exist, or stat is unsupported } else { return (float)(sumTotalTermFreq / (double)collectionStats.MaxDoc); } } /// <summary> /// The default implementation encodes <c>boost / sqrt(length)</c> /// with <see cref="SmallSingle.SingleToByte315(float)"/>. This is compatible with /// Lucene's default implementation. If you change this, then you should /// change <see cref="DecodeNormValue(byte)"/> to match. /// </summary> protected internal virtual byte EncodeNormValue(float boost, int fieldLength) { return SmallSingle.SingleToByte315(boost / (float)Math.Sqrt(fieldLength)); } /// <summary> /// The default implementation returns <c>1 / f<sup>2</sup></c> /// where <c>f</c> is <see cref="SmallSingle.Byte315ToSingle(byte)"/>. /// </summary> protected internal virtual float DecodeNormValue(byte b) { return NORM_TABLE[b & 0xFF]; } /// <summary> /// True if overlap tokens (tokens with a position of increment of zero) are /// discounted from the document's length. /// </summary> private bool discountOverlaps = true; // LUCENENET specific: made private, since value can be set/get through propery /// <summary> /// Gets or Sets whether overlap tokens (Tokens with 0 position increment) are /// ignored when computing norm. By default this is true, meaning overlap /// tokens do not count when computing norms. /// </summary> public virtual bool DiscountOverlaps { get => discountOverlaps; set => discountOverlaps = value; } /// <summary> /// Cache of decoded bytes. </summary> private static readonly float[] NORM_TABLE = LoadNormTable(); private static float[] LoadNormTable() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { float[] normTable = new float[256]; for (int i = 0; i < 256; i++) { float f = SmallSingle.SByte315ToSingle((sbyte)i); normTable[i] = 1.0f / (f * f); } return normTable; } public override sealed long ComputeNorm(FieldInvertState state) { int numTerms = discountOverlaps ? state.Length - state.NumOverlap : state.Length; return EncodeNormValue(state.Boost, numTerms); } /// <summary> /// Computes a score factor for a simple term and returns an explanation /// for that score factor. /// /// <para/> /// The default implementation uses: /// /// <code> /// Idf(docFreq, searcher.MaxDoc); /// </code> /// /// Note that <see cref="CollectionStatistics.MaxDoc"/> is used instead of /// <see cref="Lucene.Net.Index.IndexReader.NumDocs"/> because also /// <see cref="TermStatistics.DocFreq"/> is used, and when the latter /// is inaccurate, so is <see cref="CollectionStatistics.MaxDoc"/>, and in the same direction. /// In addition, <see cref="CollectionStatistics.MaxDoc"/> is more efficient to compute /// </summary> /// <param name="collectionStats"> collection-level statistics </param> /// <param name="termStats"> term-level statistics for the term </param> /// <returns> an <see cref="Explanation"/> object that includes both an idf score factor /// and an explanation for the term. </returns> public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics termStats) { long df = termStats.DocFreq; long max = collectionStats.MaxDoc; float idf = Idf(df, max); return new Explanation(idf, "idf(docFreq=" + df + ", maxDocs=" + max + ")"); } /// <summary> /// Computes a score factor for a phrase. /// /// <para/> /// The default implementation sums the idf factor for /// each term in the phrase. /// </summary> /// <param name="collectionStats"> collection-level statistics </param> /// <param name="termStats"> term-level statistics for the terms in the phrase </param> /// <returns> an <see cref="Explanation"/> object that includes both an idf /// score factor for the phrase and an explanation /// for each term. </returns> public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats) { long max = collectionStats.MaxDoc; float idf = 0.0f; Explanation exp = new Explanation(); exp.Description = "idf(), sum of:"; foreach (TermStatistics stat in termStats) { long df = stat.DocFreq; float termIdf = Idf(df, max); exp.AddDetail(new Explanation(termIdf, "idf(docFreq=" + df + ", maxDocs=" + max + ")")); idf += termIdf; } exp.Value = idf; return exp; } public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { Explanation idf = termStats.Length == 1 ? IdfExplain(collectionStats, termStats[0]) : IdfExplain(collectionStats, termStats); float avgdl = AvgFieldLength(collectionStats); // compute freq-independent part of bm25 equation across all norm values float[] cache = new float[256]; for (int i = 0; i < cache.Length; i++) { cache[i] = k1 * ((1 - b) + b * DecodeNormValue((byte)i) / avgdl); } return new BM25Stats(collectionStats.Field, idf, queryBoost, avgdl, cache); } public override sealed SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { BM25Stats bm25stats = (BM25Stats)stats; return new BM25DocScorer(this, bm25stats, context.AtomicReader.GetNormValues(bm25stats.Field)); } private class BM25DocScorer : SimScorer { private readonly BM25Similarity outerInstance; private readonly BM25Stats stats; private readonly float weightValue; // boost * idf * (k1 + 1) private readonly NumericDocValues norms; private readonly float[] cache; internal BM25DocScorer(BM25Similarity outerInstance, BM25Stats stats, NumericDocValues norms) { this.outerInstance = outerInstance; this.stats = stats; this.weightValue = stats.Weight * (outerInstance.k1 + 1); this.cache = stats.Cache; this.norms = norms; } public override float Score(int doc, float freq) { // if there are no norms, we act as if b=0 float norm = norms is null ? outerInstance.k1 : cache[(sbyte)norms.Get(doc) & 0xFF]; return weightValue * freq / (freq + norm); } public override Explanation Explain(int doc, Explanation freq) { return outerInstance.ExplainScore(doc, freq, stats, norms); } public override float ComputeSlopFactor(int distance) { return outerInstance.SloppyFreq(distance); } public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload) { return outerInstance.ScorePayload(doc, start, end, payload); } } /// <summary> /// Collection statistics for the BM25 model. </summary> private class BM25Stats : SimWeight { /// <summary> /// BM25's idf </summary> internal Explanation Idf { get; private set; } /// <summary> /// The average document length. </summary> internal float Avgdl { get; private set; } /// <summary> /// query's inner boost </summary> internal float QueryBoost { get; private set; } /// <summary> /// query's outer boost (only for explain) </summary> internal float TopLevelBoost { get; set; } /// <summary> /// weight (idf * boost) </summary> internal float Weight { get; set; } /// <summary> /// field name, for pulling norms </summary> internal string Field { get; private set; } /// <summary> /// precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl) </summary> internal float[] Cache { get; private set; } internal BM25Stats(string field, Explanation idf, float queryBoost, float avgdl, float[] cache) { this.Field = field; this.Idf = idf; this.QueryBoost = queryBoost; this.Avgdl = avgdl; this.Cache = cache; } public override float GetValueForNormalization() { // we return a TF-IDF like normalization to be nice, but we don't actually normalize ourselves. float queryWeight = Idf.Value * QueryBoost; return queryWeight * queryWeight; } public override void Normalize(float queryNorm, float topLevelBoost) { // we don't normalize with queryNorm at all, we just capture the top-level boost this.TopLevelBoost = topLevelBoost; this.Weight = Idf.Value * QueryBoost * topLevelBoost; } } private Explanation ExplainScore(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms) { Explanation result = new Explanation(); result.Description = "score(doc=" + doc + ",freq=" + freq + "), product of:"; Explanation boostExpl = new Explanation(stats.QueryBoost * stats.TopLevelBoost, "boost"); if (boostExpl.Value != 1.0f) { result.AddDetail(boostExpl); } result.AddDetail(stats.Idf); Explanation tfNormExpl = new Explanation(); tfNormExpl.Description = "tfNorm, computed from:"; tfNormExpl.AddDetail(freq); tfNormExpl.AddDetail(new Explanation(k1, "parameter k1")); if (norms is null) { tfNormExpl.AddDetail(new Explanation(0, "parameter b (norms omitted for field)")); tfNormExpl.Value = (freq.Value * (k1 + 1)) / (freq.Value + k1); } else { float doclen = DecodeNormValue((byte)norms.Get(doc)); tfNormExpl.AddDetail(new Explanation(b, "parameter b")); tfNormExpl.AddDetail(new Explanation(stats.Avgdl, "avgFieldLength")); tfNormExpl.AddDetail(new Explanation(doclen, "fieldLength")); tfNormExpl.Value = (freq.Value * (k1 + 1)) / (freq.Value + k1 * (1 - b + b * doclen / stats.Avgdl)); } result.AddDetail(tfNormExpl); result.Value = boostExpl.Value * stats.Idf.Value * tfNormExpl.Value; return result; } public override string ToString() { return "BM25(k1=" + k1 + ",b=" + b + ")"; } /// <summary> /// Returns the <c>k1</c> parameter </summary> /// <seealso cref="BM25Similarity(float, float)"/> public virtual float K1 => k1; /// <summary> /// Returns the <c>b</c> parameter </summary> /// <seealso cref="BM25Similarity(float, float)"/> public virtual float B => b; } }
// TRAP message type (SNMP version 1 only). // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. /* * Created by SharpDevelop. * User: lextm * Date: 2008/4/25 * Time: 20:30 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using Lextm.SharpSnmpLib.Security; namespace Lextm.SharpSnmpLib.Messaging { /// <summary> /// Trap message. /// </summary> public sealed class TrapV1Message : ISnmpMessage { private readonly ISnmpPdu _pdu; private readonly Sequence _container; private Scope _scope; /// <summary> /// Creates a <see cref="TrapV1Message"/> with all content. /// </summary> /// <param name="version">Protocol version</param> /// <param name="agent">Agent address</param> /// <param name="community">Community name</param> /// <param name="enterprise">Enterprise</param> /// <param name="generic">Generic</param> /// <param name="specific">Specific</param> /// <param name="time">Time</param> /// <param name="variables">Variables</param> [CLSCompliant(false)] public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList<Variable> variables) { if (variables == null) { throw new ArgumentNullException("variables"); } if (enterprise == null) { throw new ArgumentNullException("enterprise"); } if (community == null) { throw new ArgumentNullException("community"); } if (agent == null) { throw new ArgumentNullException("agent"); } if (version != VersionCode.V1) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", version), "version"); } Version = version; AgentAddress = agent; Community = community; Enterprise = enterprise; Generic = generic; Specific = specific; TimeStamp = time; var pdu = new TrapV1Pdu( Enterprise, new IP(AgentAddress.GetAddressBytes()), new Integer32((int)Generic), new Integer32(Specific), new TimeTicks(TimeStamp), variables); _pdu = pdu; Parameters = SecurityParameters.Create(Community); } /// <summary> /// Creates a <see cref="TrapV1Message"/> instance with a message body. /// </summary> /// <param name="body">Message body</param> public TrapV1Message(Sequence body) { if (body == null) { throw new ArgumentNullException("body"); } if (body.Length != 3) { throw new ArgumentException("wrong message body"); } Community = (OctetString)body[1]; Version = (VersionCode)((Integer32)body[0]).ToInt32(); // IMPORTANT: comment this check out if you need to support if (Version != VersionCode.V1) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", Version), "body"); } _pdu = (ISnmpPdu)body[2]; if (_pdu.TypeCode != SnmpType.TrapV1Pdu) { throw new ArgumentException("wrong message type"); } var trapPdu = (TrapV1Pdu)_pdu; Enterprise = trapPdu.Enterprise; AgentAddress = new IPAddress(trapPdu.AgentAddress.GetRaw()); Generic = trapPdu.Generic; Specific = trapPdu.Specific; TimeStamp = trapPdu.TimeStamp.ToUInt32(); Parameters = SecurityParameters.Create(Community); _container = body; } /// <summary> /// Time stamp. /// </summary> [CLSCompliant(false), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp")] public uint TimeStamp { get; private set; } /// <summary> /// Community name. /// </summary> public OctetString Community { get; private set; } /// <summary> /// Enterprise. /// </summary> public ObjectIdentifier Enterprise { get; private set; } /// <summary> /// Agent address. /// </summary> public IPAddress AgentAddress { get; private set; } /// <summary> /// Generic type. /// </summary> public GenericCode Generic { get; private set; } /// <summary> /// Specific type. /// </summary> public int Specific { get; private set; } /// <summary> /// Protocol version. /// </summary> public VersionCode Version { get; private set; } /// <summary> /// Gets the header. /// </summary> public Header Header { get { throw new NotSupportedException(); } } /// <summary> /// Gets the privacy provider. /// </summary> public IPrivacyProvider Privacy { get { throw new NotSupportedException(); } } /// <summary> /// To byte format. /// </summary> /// <returns></returns> public byte[] ToBytes() { return _container == null ? PackMessage(Version, Community, _pdu).ToBytes() : _container.ToBytes(); } /// <summary> /// Gets the parameters. /// </summary> /// <value>The parameters.</value> /// <remarks><see cref="TrapV1Message"/> returns null here.</remarks> public SecurityParameters Parameters { get; private set; } /// <summary> /// Gets the scope. /// </summary> /// <value>The scope.</value> /// <remarks><see cref="TrapV1Message"/> returns null here.</remarks> public Scope Scope { get { return _scope ?? (_scope = new Scope(_pdu)); } } /// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="TrapV1Message"/>. /// </summary> /// <returns></returns> public override string ToString() { return ToString(null); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="objects">The objects.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> [CLSCompliant(false)] public string ToString(IObjectRegistry objects) { return string.Format( CultureInfo.InvariantCulture, "SNMPv1 trap: {0}", ((TrapV1Pdu)_pdu).ToString(objects)); } /// <summary> /// Packs the message. /// </summary> /// <param name="version">The version.</param> /// <param name="data">The data.</param> /// <returns></returns> internal static Sequence PackMessage(VersionCode version, params ISnmpData[] data) { if (data == null) { throw new ArgumentNullException("data"); } var collection = new List<ISnmpData>(1 + data.Length) { new Integer32((int)version) }; collection.AddRange(data); return new Sequence(collection); } } }
using System; using System.Collections.Generic; using WebSocket4Net; namespace NativeClient { /// <summary> /// A call request parameters. Passed to the callbacks registered for a function called by the server. /// </summary> public class CallRequest { public CallRequest(string message, List<object> parsedMessage) { Message = message; CallID = (int)(long) parsedMessage[1]; FuncName = (string)parsedMessage[2]; Callbacks = parsedMessage[3] as List<int>; Args = parsedMessage.GetRange(4, parsedMessage.Count - 4); } public string Message; public int CallID; public string FuncName; public List<int> Callbacks; public List<object> Args; } /// <summary> /// A call reply parameters. Passed to the callbacks registered for an expected call reply. /// </summary> public class CallReply { public CallReply(string message, List<object> parsedMessage) { Message = message; CallID = (int)(long)parsedMessage[1]; Success = (bool)parsedMessage[2]; RetValue = parsedMessage[3]; } public string Message; public int CallID; public bool Success; public object RetValue; } /// <summary> /// Handles the communication with the server. /// </summary> public class Communicator { public Communicator() {} /// <summary> /// Opens a binary protocol connection. /// </summary> /// <param name="host">Server host.</param> /// <param name="port">Server port.</param> /* public void OpenConnection(string host, int port) { socket = new BPSocketAdapter(host, port); Initialize(); } */ /// <summary> /// Opens a WebSocket-JSON protocol connection. /// </summary> /// <param name="serverURI">Server URI.</param> public void OpenConnection(string serverURI) { socket = new WebSocket(serverURI); Initialize(); } public void CloseConnection() { socket.Close(); } /// <summary> /// Occurs when connection is established. /// </summary> public event EventHandler Connected; /// <summary> /// Occurs when connection is closed. /// </summary> public event EventHandler Disconnected; public bool IsConnected { get { return socket.State == WebSocketState.Open; } } /// <summary> /// Call the specified funcName with specified args. /// </summary> /// <param name="funcName">Func name.</param> /// <param name="args">Arguments.</param> public int Call(string funcName, params object[] args) { return Call(funcName, new List<int>(), args); } /// <summary> /// Call the specified funcName with specified callbacks and specified args. The callbacks argument should /// contain indicies of arguments that are names of functions registered via RegisterFunc. /// </summary> /// <param name="funcName">Func name.</param> /// <param name="callbacks">Callbacks.</param> /// <param name="args">Arguments.</param> public int Call(string funcName, List<int> callbacks, params object[] args) { int callID = GetNextCallID(); List<object> message = new List<object>(); message.Add("call"); message.Add(callID); message.Add(funcName); message.Add(callbacks); message.AddRange(args); var serializedMessage = Json.Serialize(message); socket.Send(serializedMessage); return callID; } private int GetNextCallID() { lock (nextCallIDLock) return nextCallID++; } /// <summary> /// Registers the callback for a function. Returns generated function name. /// </summary> /// <returns>Generated function name.</returns> /// <param name="callback">Callback.</param> public string RegisterFunc(Action<CallRequest> callback) { string name = Guid.NewGuid().ToString(); RegisterFunc(name, callback); return name; } /// <summary> /// Registers the callback for a function with specified name. /// </summary> /// <param name="funcName">Function name.</param> /// <param name="callback">Callback.</param> public void RegisterFunc(string funcName, Action<CallRequest> callback) { lock (registeredFuncs) registeredFuncs.Add(funcName, callback); } /// <summary> /// Adds a callback to be invoked on a call reply with specified ID. /// </summary> /// <param name="callID">Call reply ID.</param> /// <param name="callback">Callback.</param> public void AddReplyHandler(int callID, Action<CallReply> callback) { lock (expectedReplies) expectedReplies.Add(callID, callback); } void Initialize() { socket.Opened += (sender, e) => Console.WriteLine("Connected to the server"); socket.Error += (sender, e) => Console.WriteLine("Connection error", e.Exception); socket.Closed += (sender, e) => Console.WriteLine("Connection closed"); socket.MessageReceived += HandleMessage; socket.Opened += HandleOpened; socket.Closed += HandleClosed; socket.Open(); } void HandleOpened(object sender, EventArgs e) { if (Connected != null) Connected(this, new EventArgs()); } void HandleClosed(object sender, EventArgs e) { if (Disconnected != null) Disconnected(this, new EventArgs()); } void HandleCallMessage(string message, List<object> parsedMessage) { string funcName = (string)parsedMessage[2]; Action<CallRequest> callback; lock (registeredFuncs) { if (!registeredFuncs.ContainsKey(funcName)) Console.WriteLine("Unexpected func call: {0}", message); callback = registeredFuncs[funcName]; } callback(new CallRequest(message, parsedMessage)); } void HandleCallReplyMessage(string message, List<object> parsedMessage) { int callID = (int) (long) parsedMessage[1]; Action<CallReply> callback; lock (expectedReplies) { if (!expectedReplies.ContainsKey(callID)) return; callback = expectedReplies[callID]; } callback(new CallReply(message, parsedMessage)); } void HandleMessage(object sender, WebSocket4Net.MessageReceivedEventArgs e) { List<object> parsedMessage = Json.Deserialize(e.Message) as List<object>; string messageType = (string)parsedMessage[0]; try { if (messageType == "call-error") Console.WriteLine("Received error message: {0}", e.Message); else if (messageType == "call") HandleCallMessage(e.Message, parsedMessage); else if (messageType == "call-reply") HandleCallReplyMessage(e.Message, parsedMessage); } catch (Exception ex) { Console.WriteLine("Failed to parse incoming message: " + e.Message, ex); } } /// <summary> /// Underlying Web Socket connection. /// </summary> WebSocket socket; /// <summary> /// Registered functions to be invoked on call from another side. /// </summary> Dictionary<string, Action<CallRequest>> registeredFuncs = new Dictionary<string, Action<CallRequest>>(); /// <summary> /// Handlers for expected replies. /// </summary> Dictionary<int, Action<CallReply>> expectedReplies = new Dictionary<int, Action<CallReply>>(); /// <summary> /// Next call ID. Used to generate unique call IDs. /// </summary> object nextCallIDLock = new object(); int nextCallID = 0; } }
/****************************************************************************** * The MIT License * Copyright (c) 2008 Rusty Howell, Thomas Wiest * * 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. *******************************************************************************/ // Authors: // Thomas Wiest twiest@users.sourceforge.net // Rusty Howell rhowell@users.sourceforge.net using System; using System.Text; namespace UvsChess.Framework { internal class ChessState { #region Members public const string FenStartState = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; //public const string FenStartState = "rnbqkbnr/1ppppppp/8/p7/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 2"; private ChessBoard _currentBoard; private ChessBoard _previousBoard; private ChessMove _previousMove; private ChessColor _yourColor; private int _fullMoves = 0; private int _halfMoves = 0; private ChessLocation _enPassant = null; private bool _canWhiteCastleKingSide = false; private bool _canWhiteCastleQueenSide = false; private bool _canBlackCastleKingSide = false; private bool _canBlackCastleQueenSide = false; //private string _castling = "-"; #endregion #region Constructors public ChessState() : this(FenStartState) { } /// <summary> /// See: http://en.wikipedia.org/wiki/Forsyth-Edwards_Notation /// </summary> /// <param name="fenBoard"></param> public ChessState(string fenBoard) { if ((fenBoard == null) || (fenBoard == string.Empty)) { fenBoard = FenStartState; } FromFenBoard(fenBoard); } #endregion #region Properties and Indexers public ChessBoard CurrentBoard { get { return _currentBoard; } set { _currentBoard = value; } } public ChessBoard PreviousBoard { get { return _previousBoard; } set { _previousBoard = value; } } public ChessMove PreviousMove { get { return _previousMove; } set { _previousMove = value; } } public ChessColor CurrentPlayerColor { get { return _yourColor; } set { _yourColor = value; } } /// <summary> /// Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move. /// </summary> public int FullMoves { get { return _fullMoves; } set { _fullMoves = value; //Program.Log("FullMoves: " + _fullMoves); } } /// <summary> /// Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. /// This is used to determine if a draw can be claimed under the fifty move rule. /// See: http://en.wikipedia.org/wiki/Fifty_move_rule /// </summary> public int HalfMoves { get { return _halfMoves; } set { _halfMoves = value; } } /// <summary> /// Returns the ChessLocation of the available En passant move. If no En passant move is available, /// null is returned. /// See: http://en.wikipedia.org/wiki/En_passant /// </summary> public ChessLocation EnPassant { get { return _enPassant; } set { _enPassant = value; } } public bool CanWhiteCastleKingSide { get { return _canWhiteCastleKingSide; } set { _canWhiteCastleKingSide = value; } } public bool CanWhiteCastleQueenSide { get { return _canWhiteCastleQueenSide; } set { _canWhiteCastleQueenSide = value; } } public bool CanBlackCastleKingSide { get { return _canBlackCastleKingSide; } set { _canBlackCastleKingSide = value; } } public bool CanBlackCastleQueenSide { get { return _canBlackCastleQueenSide; } set { _canBlackCastleQueenSide = value; } } #endregion #region Methods and Operators public void MakeMove(ChessMove move) { PreviousMove = move; PreviousBoard = CurrentBoard.Clone(); CurrentBoard.MakeMove(move); if (CurrentPlayerColor == ChessColor.White) { CurrentPlayerColor = ChessColor.Black; } else { CurrentPlayerColor = ChessColor.White; } } /// <summary> /// Creates a deep copy of ChessState /// </summary> /// <returns></returns> public ChessState Clone() { ChessState newState = new ChessState(); if (this.CurrentBoard == null) newState.CurrentBoard = null; else newState.CurrentBoard = this.CurrentBoard.Clone(); if (this.PreviousBoard == null) newState.PreviousBoard = null; else newState.PreviousBoard = this.PreviousBoard.Clone(); if (this.PreviousMove == null) newState.PreviousMove = null; else newState.PreviousMove = this.PreviousMove.Clone(); newState.CurrentPlayerColor = this.CurrentPlayerColor; newState.CanWhiteCastleKingSide = this.CanWhiteCastleKingSide; newState.CanWhiteCastleQueenSide = this.CanWhiteCastleQueenSide; newState.CanBlackCastleKingSide = this.CanBlackCastleKingSide; newState.CanBlackCastleQueenSide = this.CanBlackCastleQueenSide; if (this.EnPassant != null) newState.EnPassant = this.EnPassant.Clone(); newState.HalfMoves = this.HalfMoves; newState.FullMoves = this.FullMoves; return newState; } #region FEN board /// <summary> /// Converts the ChessState to a FEN board /// </summary> /// <returns>FEN board</returns> public string ToFenBoard() { StringBuilder strBuild = new StringBuilder(); strBuild.Append(CurrentBoard.ToPartialFenBoard()); if (CurrentPlayerColor == ChessColor.White) { strBuild.Append(" w"); } else { strBuild.Append(" b"); } //place holder for castling (not currently supported) strBuild.Append(" " + CastlingToFen()); //place holder for en passant (not currently supported) strBuild.Append(EnPassantToFen()); //half and full moves strBuild.Append(" " + HalfMoves.ToString() + " " + FullMoves.ToString()); return strBuild.ToString(); } /// <summary> /// Sets the chess state as described in the FEN board. /// See: http://en.wikipedia.org/wiki/Forsyth-Edwards_Notation /// </summary> /// <param name="fenBoard"></param> public void FromFenBoard(string fenBoard) { string[] lines = fenBoard.Split(' '); CurrentBoard = new ChessBoard(fenBoard); if (lines[1] == "w") { CurrentPlayerColor = ChessColor.White; } else if (lines[1] == "b") { CurrentPlayerColor = ChessColor.Black; } else { throw new Exception("Missing active color in FEN board"); } //casting is lines[2] CastlingFromFen(lines[2]); //en passant is lines[3] EnPassant = EnPassantFromFen(lines[3].ToLower()); HalfMoves = Convert.ToInt32(lines[4]); FullMoves = Convert.ToInt32(lines[5]); } private void CastlingFromFen(string castling) { _canBlackCastleKingSide = false; _canBlackCastleQueenSide = false; _canWhiteCastleKingSide = false; _canWhiteCastleQueenSide = false; if (castling == "-") { return; } foreach (char c in castling) { switch(c) { case 'K': _canWhiteCastleKingSide = true; break; case 'Q': _canWhiteCastleQueenSide = true; break; case 'k': _canBlackCastleKingSide = true; break; case 'q': _canBlackCastleQueenSide = true; break; default: throw new Exception(string.Format("Invalid castling values '{0}' in fen board", castling)); } } } private string CastlingToFen() { string castling = string.Empty; castling += (_canWhiteCastleKingSide)?"K":""; castling += (_canWhiteCastleQueenSide)?"Q":""; castling += (_canBlackCastleKingSide)?"k":""; castling += (_canBlackCastleQueenSide)?"q":""; castling = (castling == string.Empty)?"-":castling; return castling; } private ChessLocation EnPassantFromFen(string fen) { if (fen == "-") { return null; } int row = Convert.ToInt32(fen[0]) - 97; int col = Convert.ToInt32(fen[1]) - 48; return new ChessLocation(row, col); } private string EnPassantToFen() { if (EnPassant == null) { return " -"; //preceding space is important } char c = Convert.ToChar(EnPassant.Y + 97); string enp = " " + c + EnPassant.X.ToString(); return enp; } #endregion public override string ToString() { if (this.PreviousMove == null) { return "Start of Game"; } else { ChessColor color = ChessColor.White; if (CurrentPlayerColor == ChessColor.White) { color = ChessColor.Black; } return string.Format("{0}: {1}",color,PreviousMove.ToString()); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Scripting.WorldComm; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.XEngine; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.ScriptEngine.Shared.Instance.Tests { /// <summary> /// Test that co-operative script thread termination is working correctly. /// </summary> [TestFixture] public class CoopTerminationTests : OpenSimTestCase { private TestScene m_scene; private OpenSim.Region.ScriptEngine.XEngine.XEngine m_xEngine; private AutoResetEvent m_chatEvent; private AutoResetEvent m_stoppedEvent; private OSChatMessage m_osChatMessageReceived; /// <summary> /// Number of chat messages received so far. Reset before each test. /// </summary> private int m_chatMessagesReceived; /// <summary> /// Number of chat messages expected. m_chatEvent is not fired until this number is reached or exceeded. /// </summary> private int m_chatMessagesThreshold; [SetUp] public void Init() { m_osChatMessageReceived = null; m_chatMessagesReceived = 0; m_chatMessagesThreshold = 0; m_chatEvent = new AutoResetEvent(false); m_stoppedEvent = new AutoResetEvent(false); //AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory + "/bin"); // Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); m_xEngine = new OpenSim.Region.ScriptEngine.XEngine.XEngine(); IniConfigSource configSource = new IniConfigSource(); IConfig startupConfig = configSource.AddConfig("Startup"); startupConfig.Set("DefaultScriptEngine", "XEngine"); IConfig xEngineConfig = configSource.AddConfig("XEngine"); xEngineConfig.Set("Enabled", "true"); xEngineConfig.Set("StartDelay", "0"); // These tests will not run with AppDomainLoading = true, at least on mono. For unknown reasons, the call // to AssemblyResolver.OnAssemblyResolve fails. xEngineConfig.Set("AppDomainLoading", "false"); xEngineConfig.Set("ScriptStopStrategy", "co-op"); // Make sure loops aren't actually being terminated by a script delay wait. xEngineConfig.Set("ScriptDelayFactor", 0); // This is really just set for debugging the test. xEngineConfig.Set("WriteScriptSourceToDebugFile", true); // Set to false if we need to debug test so the old scripts don't get wiped before each separate test // xEngineConfig.Set("DeleteScriptsOnStartup", false); // This is not currently used at all for co-op termination. Bumping up to demonstrate that co-op termination // has an effect - without it tests will fail due to a 120 second wait for the event to finish. xEngineConfig.Set("WaitForEventCompletionOnScriptStop", 120000); m_scene = new SceneHelpers().SetupScene("My Test", TestHelpers.ParseTail(0x9999), 1000, 1000, configSource); SceneHelpers.SetupSceneModules(m_scene, configSource, m_xEngine); m_scene.StartScripts(); } /// <summary> /// Test co-operative termination on derez of an object containing a script with a long-running event. /// </summary> /// <remarks> /// TODO: Actually compiling the script is incidental to this test. Really want a way to compile test scripts /// within the build itself. /// </remarks> [Test] public void TestStopOnLongSleep() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { llSay(0, ""Thin Lizzy""); llSleep(60); } }"; TestStop(script); } [Test] public void TestNoStopOnSingleStatementForLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; for (i = 0; i <= 1; i++) llSay(0, ""Iter "" + (string)i); } }"; TestSingleStatementNoStop(script); } [Test] public void TestStopOnLongSingleStatementForLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); for (i = 0; i < 2147483647; i++) llSay(0, ""Iter "" + (string)i); } }"; TestStop(script); } [Test] public void TestStopOnLongCompoundStatementForLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); for (i = 0; i < 2147483647; i++) { llSay(0, ""Iter "" + (string)i); } } }"; TestStop(script); } [Test] public void TestNoStopOnSingleStatementWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; while (i < 2) llSay(0, ""Iter "" + (string)i++); } }"; TestSingleStatementNoStop(script); } [Test] public void TestStopOnLongSingleStatementWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); while (1 == 1) llSay(0, ""Iter "" + (string)i++); } }"; TestStop(script); } [Test] public void TestStopOnLongCompoundStatementWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); while (1 == 1) { llSay(0, ""Iter "" + (string)i++); } } }"; TestStop(script); } [Test] public void TestNoStopOnSingleStatementDoWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; do llSay(0, ""Iter "" + (string)i++); while (i < 2); } }"; TestSingleStatementNoStop(script); } [Test] public void TestStopOnLongSingleStatementDoWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); do llSay(0, ""Iter "" + (string)i++); while (1 == 1); } }"; TestStop(script); } [Test] public void TestStopOnLongCompoundStatementDoWhileLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); do { llSay(0, ""Iter "" + (string)i++); } while (1 == 1); } }"; TestStop(script); } [Test] public void TestStopOnInfiniteJumpLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); @p1; llSay(0, ""Iter "" + (string)i++); jump p1; } }"; TestStop(script); } // Disabling for now as these are not particularly useful tests (since they fail due to stack overflow before // termination can even be tried. // [Test] public void TestStopOnInfiniteUserFunctionCallLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @" integer i = 0; ufn1() { llSay(0, ""Iter ufn1() "" + (string)i++); ufn1(); } default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); ufn1(); } }"; TestStop(script); } // Disabling for now as these are not particularly useful tests (since they fail due to stack overflow before // termination can even be tried. // [Test] public void TestStopOnInfiniteManualEventCallLoop() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string script = @"default { state_entry() { integer i = 0; llSay(0, ""Thin Lizzy""); llSay(0, ""Iter"" + (string)i++); default_event_state_entry(); } }"; TestStop(script); } private SceneObjectPart CreateScript(string script, string itemName, UUID userId) { // UUID objectId = TestHelpers.ParseTail(0x100); // UUID itemId = TestHelpers.ParseTail(0x3); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, string.Format("Object for {0}", itemName), 0x100); m_scene.AddNewSceneObject(so, true); InventoryItemBase itemTemplate = new InventoryItemBase(); // itemTemplate.ID = itemId; itemTemplate.Name = itemName; itemTemplate.Folder = so.UUID; itemTemplate.InvType = (int)InventoryType.LSL; m_scene.EventManager.OnChatFromWorld += OnChatFromWorld; return m_scene.RezNewScript(userId, itemTemplate, script); } private void TestSingleStatementNoStop(string script) { // In these tests we expect to see at least 2 chat messages to confirm that the loop is working properly. m_chatMessagesThreshold = 2; UUID userId = TestHelpers.ParseTail(0x1); // UUID objectId = TestHelpers.ParseTail(0x100); // UUID itemId = TestHelpers.ParseTail(0x3); string itemName = "TestNoStop"; SceneObjectPart partWhereRezzed = CreateScript(script, itemName, userId); // Wait for the script to start the event before we try stopping it. m_chatEvent.WaitOne(60000); if (m_osChatMessageReceived == null) Assert.Fail("Script did not start"); else Assert.That(m_chatMessagesReceived, Is.EqualTo(2)); bool running; TaskInventoryItem scriptItem = partWhereRezzed.Inventory.GetInventoryItem(itemName); Assert.That( SceneObjectPartInventory.TryGetScriptInstanceRunning(m_scene, scriptItem, out running), Is.True); Assert.That(running, Is.True); } private void TestStop(string script) { // In these tests we're only interested in the first message to confirm that the script has started. m_chatMessagesThreshold = 1; UUID userId = TestHelpers.ParseTail(0x1); // UUID objectId = TestHelpers.ParseTail(0x100); // UUID itemId = TestHelpers.ParseTail(0x3); string itemName = "TestStop"; SceneObjectPart partWhereRezzed = CreateScript(script, itemName, userId); TaskInventoryItem rezzedItem = partWhereRezzed.Inventory.GetInventoryItem(itemName); // Wait for the script to start the event before we try stopping it. m_chatEvent.WaitOne(60000); if (m_osChatMessageReceived != null) Console.WriteLine("Script started with message [{0}]", m_osChatMessageReceived.Message); else Assert.Fail("Script did not start"); // FIXME: This is a very poor way of trying to avoid a low-probability race condition where the script // executes llSay() but has not started the next statement before we try to stop it. Thread.Sleep(1000); // We need a way of carrying on if StopScript() fail, since it won't return if the script isn't actually // stopped. This kind of multi-threading is far from ideal in a regression test. new Thread(() => { m_xEngine.StopScript(rezzedItem.ItemID); m_stoppedEvent.Set(); }).Start(); if (!m_stoppedEvent.WaitOne(30000)) Assert.Fail("Script did not co-operatively stop."); bool running; TaskInventoryItem scriptItem = partWhereRezzed.Inventory.GetInventoryItem(itemName); Assert.That( SceneObjectPartInventory.TryGetScriptInstanceRunning(m_scene, scriptItem, out running), Is.True); Assert.That(running, Is.False); } private void OnChatFromWorld(object sender, OSChatMessage oscm) { Console.WriteLine("Got chat [{0}]", oscm.Message); m_osChatMessageReceived = oscm; if (++m_chatMessagesReceived >= m_chatMessagesThreshold) { m_scene.EventManager.OnChatFromWorld -= OnChatFromWorld; m_chatEvent.Set(); } } } }
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel // // 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.Text.RegularExpressions; using System.Xml; using SharpDoc.Logging; using SharpDoc.Model; using SharpRazor; namespace SharpDoc { /// <summary> /// Template context used by all templates. /// </summary> public class TemplateContext { private const string StyleDirectory = "Styles"; private List<TagExpandItem> _regexItems; private MsdnRegistry _msnRegistry; private bool assembliesProcessed; private bool topicsProcessed; /// <summary> /// Initializes a new instance of the <see cref="TemplateContext"/> class. /// </summary> public TemplateContext(Razorizer razorizer) { this.Razorizer = razorizer; StyleDirectories = new List<string>(); _regexItems = new List<TagExpandItem>(); _msnRegistry = new MsdnRegistry(); Param = new DynamicParam(); Style = new DynamicParam(); razorizer.TemplateResolver += TemplateResolver; } /// <summary> /// Finds a <see cref="IModelReference"/> from an id. /// </summary> /// <param name="id">The id.</param> /// <returns> /// A registered reference or null if it's an external or invalid reference /// </returns> private IModelReference FindLocalReference(string id) { var reference = Registry.FindById(id); if (reference == null) reference = Registry.FindByFileName(id); return reference; } public Razorizer Razorizer { get; private set; } /// <summary> /// Gets the param dynamic properties. /// </summary> /// <value>The param dynamic properties.</value> public dynamic Param { get; private set; } /// <summary> /// Gets the style dynamic properties. /// </summary> /// <value>The style dynamic properties.</value> public dynamic Style { get; private set; } /// <summary> /// Gets or sets the style manager. /// </summary> /// <value>The style manager.</value> public StyleManager StyleManager { get; set; } /// <summary> /// Gets or sets the registry. /// </summary> /// <value>The registry.</value> public MemberRegistry Registry { get; set; } /// <summary> /// Gets or sets the topics. /// </summary> /// <value>The topics.</value> public NTopic RootTopic { get; set; } /// <summary> /// Gets or sets the search topic. /// </summary> /// <value>The search topic.</value> public NTopic SearchTopic { get; set;} /// <summary> /// Gets or sets the class library topic. /// </summary> /// <value> /// The class library topic. /// </value> public NTopic ClassLibraryTopic { get; set; } /// <summary> /// Gets or sets the assemblies. /// </summary> /// <value>The assemblies.</value> public List<NNamespace> Namespaces { get; set; } /// <summary> /// Gets or sets the current topic. /// </summary> /// <value>The current topic.</value> public NTopic Topic { get; set; } /// <summary> /// Gets or sets the current assembly being processed. /// </summary> /// <value>The current assembly being processed.</value> public NAssembly Assembly { get; set; } /// <summary> /// Gets or sets the current namespace being processed. /// </summary> /// <value>The current namespace being processed.</value> public NNamespace Namespace { get; set; } /// <summary> /// Gets or sets the current type being processed. /// </summary> /// <value>The current type being processed.</value> public NType Type { get; set; } /// <summary> /// Gets or sets the current member being processed. /// </summary> /// <value>The current member.</value> public NMember Member { get; set; } /// <summary> /// Gets or sets the style directories. /// </summary> /// <value>The style directories.</value> private List<string> StyleDirectories {get; set;} /// <summary> /// Gets or sets the output directory. /// </summary> /// <value>The output directory.</value> public string OutputDirectory { get; set; } /// <summary> /// Gets or sets the link resolver. /// </summary> /// <value>The link resolver.</value> public Func<LinkDescriptor, string> LinkResolver { get; set; } /// <summary> /// Gets or sets the page id function. /// </summary> /// <value> /// The page id function. /// </value> public Func<IModelReference, string> PageIdFunction { get; set; } /// <summary> /// Gets or sets the write to function. /// </summary> /// <value> /// The write to function. /// </value> public Action<IModelReference, string> WriteTo { get; set; } /// <summary> /// Gets or sets the index file. /// </summary> /// <value> /// The index file. /// </value> public TextWriter IndexFile { get; set; } /// <summary> /// Gets or sets the function that get the content of a page of the extern documentation site. /// </summary> /// <value> /// The function that get the content of a page of the extern documentation site. /// </value> public Func<XmlNode, bool, string> GetWebDocContent { get; set; } /// <summary> /// Gets or sets the web documentation. /// </summary> /// <value>The web documentation.</value> public WebDocumentation WebDocumentation { get; set; } /// <summary> /// Gets or sets the name of the current style. /// </summary> /// <value> /// The name of the current style. /// </value> public string CurrentStyleName { get; set; } /// <summary> /// Gets or sets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; set; } private ModelProcessor modelProcessor; private TopicBuilder topicBuilder; /// <summary> /// Initializes this instance. /// </summary> public void Initialize() { Config.FilePath = Config.FilePath ?? Path.Combine(Environment.CurrentDirectory, "unknown.xml"); OutputDirectory = Config.AbsoluteOutputDirectory; // Set title Param.Title = Config.Title; // Add parameters if (Config.Parameters.Count > 0) { var dictionary = (DynamicParam)Param; foreach (var configParam in Config.Parameters) { dictionary.Properties.Remove(configParam.Name); dictionary.Properties.Add(configParam.Name, configParam.value); } } // Add styles if (Config.StyleParameters.Count > 0) { var dictionary = (IDictionary<string, object>)Style; foreach (var configParam in Config.StyleParameters) { dictionary.Remove(configParam.Name); dictionary.Add(configParam.Name, configParam.value); } } } /// <summary> /// Processes the assemblies. /// </summary> public void ProcessAssemblies() { if (!assembliesProcessed) { // Process the assemblies modelProcessor = new ModelProcessor { AssemblyManager = new MonoCecilAssemblyManager(), ModelBuilder = new MonoCecilModelBuilder(), PageIdFunction = PageIdFunction }; modelProcessor.Run(Config); if (Logger.HasErrors) Logger.Fatal("Too many errors in config file. Check previous message."); Namespaces = new List<NNamespace>(modelProcessor.Namespaces); Registry = modelProcessor.Registry; assembliesProcessed = true; } } /// <summary> /// Processes the topics. /// </summary> public void ProcessTopics() { if (!topicsProcessed) { // Build the topics topicBuilder = new TopicBuilder() { Namespaces = modelProcessor.Namespaces, Registry = modelProcessor.Registry }; topicBuilder.Run(Config, PageIdFunction); if (Logger.HasErrors) Logger.Fatal("Too many errors in config file. Check previous message."); RootTopic = topicBuilder.RootTopic; SearchTopic = topicBuilder.SearchTopic; ClassLibraryTopic = topicBuilder.ClassLibraryTopic; topicsProcessed = true; } } /// <summary> /// Finds the topic by id. /// </summary> /// <param name="topicId">The topic id.</param> /// <returns></returns> public NTopic FindTopicById(string topicId) { if (RootTopic == null) return null; return RootTopic.FindTopicById(topicId); } /// <summary> /// Gets the current context. /// </summary> /// <value>The current context.</value> public IModelReference CurrentContext { get { if (Type != null) return Type; if (Namespace != null) return Namespace; if (Assembly != null) return Assembly; if (Topic != null) return Topic; return null; } } /// <summary> /// Resolve a local element Id (i.e. "T:System.Object") to a URL. /// </summary> /// <param name="reference">The reference.</param> /// <param name="linkName">Name of the link.</param> /// <param name="forceLocal">if set to <c>true</c> [force local].</param> /// <param name="attributes">The attributes.</param> /// <param name="useSelf">if set to <c>true</c> [use self when possible].</param> /// <returns></returns> public string ToUrl(IModelReference reference, string linkName = null, bool forceLocal = false, string attributes = null, bool useSelf = true) { return ToUrl(reference.Id, linkName, forceLocal, attributes, reference, useSelf); } /// <summary> /// Resolve a document Id (i.e. "T:System.Object") to an URL. /// </summary> /// <param name="id">The id.</param> /// <param name="linkName">Name of the link.</param> /// <param name="forceLocal">if set to <c>true</c> [force local].</param> /// <param name="attributes">The attributes.</param> /// <param name="localReference">The local reference.</param> /// <param name="useSelf"></param> /// <returns></returns> public string ToUrl(string id, string linkName = null, bool forceLocal = false, string attributes = null, IModelReference localReference = null, bool useSelf = true) { if (string.IsNullOrWhiteSpace(id)) return "#"; id = id.Trim(); if (id.StartsWith("!:")) id = id.Substring(2); if (id.Length == 0 || id == "#") return linkName ?? id; var linkDescriptor = new LinkDescriptor { Type = LinkType.None, Index = -1 }; var typeReference = localReference as INTypeReference; INTypeReference genericInstance = null; bool isGenericInstance = typeReference != null && typeReference.IsGenericInstance; bool isGenericParameter = typeReference != null && typeReference.IsGenericParameter; if (isGenericInstance) { var elementType = typeReference.ElementType; id = elementType.Id; genericInstance = typeReference; linkName = elementType.Name.Substring(0, elementType.Name.IndexOf('<')); } linkDescriptor.LocalReference = FindLocalReference(id); if (isGenericParameter) { linkDescriptor.Name = typeReference.Name; } else if (linkDescriptor.LocalReference != null) { // For local references, use short name var method = linkDescriptor.LocalReference as NMethod; if (method != null) linkDescriptor.Name = method.Signature; else linkDescriptor.Name = linkDescriptor.LocalReference.Name; linkDescriptor.PageId = linkDescriptor.LocalReference.PageId; linkDescriptor.Type = LinkType.Local; linkDescriptor.Index = linkDescriptor.LocalReference.Index; if (!forceLocal && CurrentContext != null && linkDescriptor.LocalReference is NMember) { var declaringType = ((NMember) linkDescriptor.LocalReference).DeclaringType; // If link is self referencing the current context, then use a self link if ((id == CurrentContext.Id || (declaringType != null && declaringType.Id == CurrentContext.Id && (!id.StartsWith("T:") && !declaringType.Id.StartsWith("T:")))) && useSelf) { linkDescriptor.Type = LinkType.Self; } } } else { linkDescriptor.Type = LinkType.External; if (id.StartsWith("http:") || id.StartsWith("https:")) { linkDescriptor.Location = id; } else { // Try to resolve to MSDN linkDescriptor.Location = _msnRegistry.FindUrl(id); var reference = TextReferenceUtility.CreateReference(id); if (linkDescriptor.Location != null) { linkDescriptor.Name = reference.FullName; // Open MSDN documentation to a new window attributes = (attributes ?? "") + " target='_blank'"; } else { linkDescriptor.Name = reference.Name; } } } if (LinkResolver == null) { Logger.Warning("Model.LinkResolver must be set"); return id; } if (linkName != null) linkDescriptor.Name = linkName; linkDescriptor.Id = id; linkDescriptor.Attributes = attributes; var urlBuilder = new StringBuilder(); urlBuilder.Append(LinkResolver(linkDescriptor)); // Handle URL for generic instance if (genericInstance != null) { urlBuilder.Append("&lt;"); for (int i = 0; i < genericInstance.GenericArguments.Count; i++) { if (i > 0) urlBuilder.Append(", "); var genericArgument = genericInstance.GenericArguments[i]; // Recursive call here urlBuilder.Append(ToUrl(genericArgument)); } urlBuilder.Append("&gt;"); } return urlBuilder.ToString(); } /// <summary> /// Uses the style. /// </summary> /// <param name="styleName">Name of the style.</param> /// <returns></returns> internal void UseStyle(string styleName) { if (!StyleManager.StyleExist(styleName)) Logger.Fatal("Cannot us style [{0}]. Style doesn't exist", styleName); CurrentStyleName = styleName; StyleDirectories.Clear(); var includeBaseStyle = new List<string>(); var styles = StyleManager.AvailableStyles; includeBaseStyle.Add(styleName); bool isNotComplete = true; // Compute directories to look, by following // In the same order they are declared while (isNotComplete) { isNotComplete = false; // Build directories to look for this specific style and all its base style); var toRemove = new List<StyleDefinition>(); foreach (var style in styles) { // Apply parameter inherited from style if (style.Name == styleName) { foreach (var parameter in style.Parameters) { ((DynamicParam)Param).Properties.Remove(parameter.Name); ((DynamicParam)Param).Properties.Add(parameter.Name, parameter.value); } } if (includeBaseStyle.Contains(style.Name)) { toRemove.Add(style); StyleDirectories.Add(style.DirectoryPath); isNotComplete = true; if (style.HasBaseStyle) includeBaseStyle.Add(style.BaseStyle); } } // Remove the style that was processed by the previous loop foreach (var styleDefinition in toRemove) styles.Remove(styleDefinition); } foreach (var styleDirectory in StyleDirectories) { Logger.Message("Using Style Directory [{0}]", styleDirectory); } } /// <summary> /// Resolves a path from template directories. /// </summary> /// <param name="path">The path.</param> /// <returns>The path to the file or directory</returns> public string ResolvePath(string path) { for (int i = 0; i < StyleDirectories.Count; i++) { string filePath = Path.Combine(StyleDirectories[i], path); if (File.Exists(filePath)) return filePath; } return null; } /// <summary> /// Resolves and load a file from template directories. /// </summary> /// <param name="file">The file.</param> /// <returns>The content of the file</returns> public string Loadfile(string file) { string filePath = ResolvePath(file); if (filePath == null) { Logger.Fatal("Cannot find file [{0}] from the following Template Directories [{1}]", file, string.Join(",", StyleDirectories)); // Fatal is stopping the process return ""; } return File.ReadAllText(filePath); } /// <summary> /// Gets the template. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public string GetTemplate(string name, out string location) { location = ResolvePath(name + ".cshtml"); if (location == null) location = ResolvePath(Path.Combine("html", name + ".cshtml")); if (location == null) { Logger.Fatal("Cannot find template [{0}] from the following Template Directories [{1}]", name, string.Join(",", StyleDirectories)); // Fatal is stopping the process return ""; } return File.ReadAllText(location); } /// <summary> /// Copies the content of the directory from all template directories. /// using inheritance directory. /// </summary> /// <param name="directoryName">Name of the directory.</param> public void CopyStyleContent(string directoryName) { for (int i = StyleDirectories.Count - 1; i >=0; i--) { var templateDirectory = StyleDirectories[i]; string filePath = Path.Combine(templateDirectory, directoryName); if (Directory.Exists(filePath)) { CopyDirectory(filePath, OutputDirectory, true); } } } /// <summary> /// Copies the content of a local directory to the destination html directory. /// </summary> /// <param name="directoryNameOrFile">Name of the source directory.</param> /// <param name="toDirectory">Name of the destination directory.</param> public void CopyLocalContent(string directoryNameOrFile, string toDirectory) { var fileOrDir = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Config.FilePath), directoryNameOrFile)); var absoulteDirectory = Path.Combine(Config.AbsoluteOutputDirectory, toDirectory); if (File.Exists(fileOrDir)) { Logger.Message("Copying file from [{0}] to [{1}]", directoryNameOrFile, toDirectory); File.Copy(fileOrDir, absoulteDirectory, true); } else { CopyDirectory(fileOrDir, absoulteDirectory, true); } } public void CopyDirectory(string from, string to, bool includeFromDir = false) { // string source, destination; - folder paths int basePathIndex = (includeFromDir ? from.Trim('/','\\').LastIndexOf('\\') : from.Length) + 1; foreach (string filePath in Directory.GetFiles(from, "*.*", SearchOption.AllDirectories)) { string subPath = filePath.Substring(basePathIndex); string newpath = Path.Combine(to, subPath); string dirPath = Path.GetDirectoryName(newpath); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); Logger.Message("Copying file from [{0}] to [{1}]", subPath, newpath); File.Copy(filePath, newpath, true); } } // private List<> private class TagExpandItem { public TagExpandItem(Regex expression, string replaceString, bool isOnlyForHtmlContent) { Expression = expression; ReplaceString = replaceString; IsOnlyForHtmlContent = isOnlyForHtmlContent; } public TagExpandItem(Regex expression, MatchEvaluator replaceEvaluator, bool isOnlyForHtmlContent) { Expression = expression; ReplaceEvaluator = replaceEvaluator; IsOnlyForHtmlContent = isOnlyForHtmlContent; } public readonly bool IsOnlyForHtmlContent; Regex Expression; string ReplaceString; MatchEvaluator ReplaceEvaluator; public string Replace(string content) { if (content == null) return null; if (ReplaceString != null) return Expression.Replace(content, ReplaceString); return Expression.Replace(content, ReplaceEvaluator); } } /// <summary> /// Add regular expression for TagExpand function. /// </summary> /// <param name="regexp">The regexp.</param> /// <param name="substitution">The substitution.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> public void RegisterTagResolver(string regexp, string substitution, bool isOnlyForHtmlContent = false) { _regexItems.Add(new TagExpandItem(new Regex(regexp), substitution, isOnlyForHtmlContent)); } /// <summary> /// Add regular expression for RegexExpand function. /// </summary> /// <param name="regexp">The regexp.</param> /// <param name="evaluator">The evaluator.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> public void RegisterTagResolver(string regexp, MatchEvaluator evaluator, bool isOnlyForHtmlContent = false) { _regexItems.Add(new TagExpandItem(new Regex(regexp), evaluator, isOnlyForHtmlContent)); } /// <summary> /// Perform regular expression expansion. /// </summary> /// <param name="content">The content to replace.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> /// <returns>The content replaced</returns> public string TagExpand(string content, bool isOnlyForHtmlContent = false) { foreach (var regexItem in _regexItems) { if (regexItem.IsOnlyForHtmlContent == isOnlyForHtmlContent) { content = regexItem.Replace(content); } } return content; } /// <summary> /// Parses the specified template name. /// </summary> /// <param name="templateName">Name of the template.</param> /// <returns></returns> public string Parse(string templateName) { string location = null; try { var template = Razorizer.FindTemplate(templateName); template.Model = this; return template.Run(); } catch (TemplateCompilationException ex) { foreach (var compilerError in ex.Errors) { Logger.PushLocation(location, compilerError.Line, compilerError.Column); if (compilerError.IsWarning) { Logger.Warning("{0}: {1}", compilerError.ErrorNumber, compilerError.ErrorText); } else { Logger.Error("{0}: {1}", compilerError.ErrorNumber, compilerError.ErrorText); } Logger.PopLocation(); } Logger.PopLocation(); Logger.Fatal("Error when compiling template [{0}]", templateName); } catch (TemplateParsingException ex) { foreach (var parserError in ex.Errors) { Logger.PushLocation(ex.Location, parserError.Location.LineIndex, parserError.Location.CharacterIndex); Logger.Error("{0}: {1}", "R0000", parserError.Message); Logger.PopLocation(); } Logger.PopLocation(); Logger.Fatal("Error when compiling template [{0}]", templateName); } catch (Exception ex) { Logger.PushLocation(location); Logger.Error("Unexpected exception", ex); Logger.PopLocation(); throw; } return ""; } private PageTemplate TemplateResolver(string templateName) { string location = null; string templateContent = GetTemplate(templateName, out location); var template = Razorizer.Compile(templateName, templateContent, location); template.Model = this; return template; } public void debug() {var i = 1;} public void debug2() {var i = 2;} } }
using Lucene.Net.Index; using Lucene.Net.Util; using System; using System.Text; namespace Lucene.Net.Documents { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Describes the properties of a field. /// </summary> public class FieldType : IIndexableFieldType { // LUCENENET specific: Moved the NumericType enum outside of this class private bool indexed; private bool stored; private bool tokenized = true; private bool storeTermVectors; private bool storeTermVectorOffsets; private bool storeTermVectorPositions; private bool storeTermVectorPayloads; private bool omitNorms; private IndexOptions indexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; private NumericType numericType; private bool frozen; private int numericPrecisionStep = NumericUtils.PRECISION_STEP_DEFAULT; private DocValuesType docValueType; /// <summary> /// Create a new mutable <see cref="FieldType"/> with all of the properties from <paramref name="ref"/> /// </summary> public FieldType(FieldType @ref) { this.indexed = @ref.IsIndexed; this.stored = @ref.IsStored; this.tokenized = @ref.IsTokenized; this.storeTermVectors = @ref.StoreTermVectors; this.storeTermVectorOffsets = @ref.StoreTermVectorOffsets; this.storeTermVectorPositions = @ref.StoreTermVectorPositions; this.storeTermVectorPayloads = @ref.StoreTermVectorPayloads; this.omitNorms = @ref.OmitNorms; this.indexOptions = @ref.IndexOptions; this.docValueType = @ref.DocValueType; this.numericType = @ref.NumericType; // Do not copy frozen! } /// <summary> /// Create a new <see cref="FieldType"/> with default properties. /// </summary> public FieldType() { } private void CheckIfFrozen() { if (frozen) { throw new InvalidOperationException("this FieldType is already frozen and cannot be changed"); } } /// <summary> /// Prevents future changes. Note, it is recommended that this is called once /// the <see cref="FieldType"/>'s properties have been set, to prevent unintentional state /// changes. /// </summary> public virtual void Freeze() { this.frozen = true; } /// <summary> /// Set to <c>true</c> to index (invert) this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsIndexed { get => this.indexed; set { CheckIfFrozen(); this.indexed = value; } } /// <summary> /// Set to <c>true</c> to store this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsStored { get => this.stored; set { CheckIfFrozen(); this.stored = value; } } /// <summary> /// Set to <c>true</c> to tokenize this field's contents via the /// configured <see cref="Analysis.Analyzer"/>. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsTokenized { get => this.tokenized; set { CheckIfFrozen(); this.tokenized = value; } } /// <summary> /// Set to <c>true</c> if this field's indexed form should be also stored /// into term vectors. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectors { get => this.storeTermVectors; set { CheckIfFrozen(); this.storeTermVectors = value; } } /// <summary> /// Set to <c>true</c> to also store token character offsets into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorOffsets { get => this.storeTermVectorOffsets; set { CheckIfFrozen(); this.storeTermVectorOffsets = value; } } /// <summary> /// Set to <c>true</c> to also store token positions into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorPositions { get => this.storeTermVectorPositions; set { CheckIfFrozen(); this.storeTermVectorPositions = value; } } /// <summary> /// Set to <c>true</c> to also store token payloads into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorPayloads { get => this.storeTermVectorPayloads; set { CheckIfFrozen(); this.storeTermVectorPayloads = value; } } /// <summary> /// Set to <c>true</c> to omit normalization values for the field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool OmitNorms { get => this.omitNorms; set { CheckIfFrozen(); this.omitNorms = value; } } /// <summary> /// Sets the indexing options for the field. /// <para/> /// The default is <see cref="IndexOptions.DOCS_AND_FREQS_AND_POSITIONS"/>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual IndexOptions IndexOptions { get => this.indexOptions; set { CheckIfFrozen(); this.indexOptions = value; } } /// <summary> /// Specifies the field's numeric type, or set to <c>null</c> if the field has no numeric type. /// If non-null then the field's value will be indexed numerically so that /// <see cref="Search.NumericRangeQuery"/> can be used at search time. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual NumericType NumericType { get => this.numericType; set { CheckIfFrozen(); numericType = value; } } /// <summary> /// Sets the numeric precision step for the field. /// <para/> /// This has no effect if <see cref="NumericType"/> returns <see cref="NumericType.NONE"/>. /// <para/> /// The default is <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/>. /// </summary> /// <exception cref="ArgumentException"> if precisionStep is less than 1. </exception> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual int NumericPrecisionStep { get => numericPrecisionStep; set { CheckIfFrozen(); if (value < 1) { throw new ArgumentException("precisionStep must be >= 1 (got " + value + ")"); } this.numericPrecisionStep = value; } } /// <summary> /// Prints a <see cref="FieldType"/> for human consumption. </summary> public override sealed string ToString() { var result = new StringBuilder(); if (IsStored) { result.Append("stored"); } if (IsIndexed) { if (result.Length > 0) { result.Append(","); } result.Append("indexed"); if (IsTokenized) { result.Append(",tokenized"); } if (StoreTermVectors) { result.Append(",termVector"); } if (StoreTermVectorOffsets) { result.Append(",termVectorOffsets"); } if (StoreTermVectorPositions) { result.Append(",termVectorPosition"); if (StoreTermVectorPayloads) { result.Append(",termVectorPayloads"); } } if (OmitNorms) { result.Append(",omitNorms"); } if (indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) { result.Append(",indexOptions="); // LUCENENET: duplcate what would happen if you print a null indexOptions in Java result.Append(indexOptions != IndexOptions.NONE ? indexOptions.ToString() : string.Empty); } if (numericType != NumericType.NONE) { result.Append(",numericType="); result.Append(numericType); result.Append(",numericPrecisionStep="); result.Append(numericPrecisionStep); } } if (docValueType != DocValuesType.NONE) { if (result.Length > 0) { result.Append(","); } result.Append("docValueType="); result.Append(docValueType); } return result.ToString(); } /// <summary> /// Sets the field's <see cref="DocValuesType"/>, or set to <see cref="DocValuesType.NONE"/> if no <see cref="DocValues"/> should be stored. /// <para/> /// The default is <see cref="DocValuesType.NONE"/> (no <see cref="DocValues"/>). /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual DocValuesType DocValueType { get => docValueType; set { CheckIfFrozen(); docValueType = value; } } } /// <summary> /// Data type of the numeric value /// @since 3.2 /// </summary> public enum NumericType { /// <summary> /// No numeric type will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, /// <summary> /// 32-bit integer numeric type /// <para/> /// NOTE: This was INT in Lucene /// </summary> INT32, /// <summary> /// 64-bit long numeric type /// <para/> /// NOTE: This was LONG in Lucene /// </summary> INT64, /// <summary> /// 32-bit float numeric type /// <para/> /// NOTE: This was FLOAT in Lucene /// </summary> SINGLE, /// <summary> /// 64-bit double numeric type </summary> DOUBLE } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class RangeTests { public class Range006 { private static int Range001() { var rst1 = Enumerable.Range(-1, 2); var rst2 = Enumerable.Range(-1, 2); return Verification.Allequal(rst1, rst2); } private static int Range002() { var rst1 = Enumerable.Range(0, 0); var rst2 = Enumerable.Range(0, 0); return Verification.Allequal(rst1, rst2); } public static int Main() { int ret = RunTest(Range001) + RunTest(Range002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Range1 { // count<0 public static int Test1() { int start = 5; int count = -1; // Throws an Exception int[] expected = { }; try { var actual = Enumerable.Range(start, count); return 1; } catch (ArgumentOutOfRangeException aoore) { if (aoore.CompareParamName("count")) return 0; else return 1; } } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Range2 { // start+count-1 is greater than int.MaxValue public static int Test2() { int start = Int32.MaxValue - 10; int count = 20; // Throws an Exception int[] expected = { }; try { var actual = Enumerable.Range(start, count); return 1; } catch (ArgumentOutOfRangeException aoore) { if (aoore.CompareParamName("count")) return 0; else return 1; } } public static int Main() { return Test2(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Range3 { // count=0 public static int Test3() { int start = 5; int count = 0; int[] expected = { }; var actual = Enumerable.Range(start, count); return Verification.Allequal(expected, actual); } public static int Main() { return Test3(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Range4 { // count=1 and start<0 public static int Test4() { int start = -5; int count = 1; int[] expected = { -5 }; var actual = Enumerable.Range(start, count); return Verification.Allequal(expected, actual); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Range5 { // count>1 public static int Test5() { int start = 12; int count = 6; int[] expected = { 12, 13, 14, 15, 16, 17 }; var actual = Enumerable.Range(start, count); return Verification.Allequal(expected, actual); } public static int Main() { return Test5(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; namespace System { // Summary: // Defines methods that convert the value of the implementing reference or value // type to a common language runtime type that has an equivalent value. public interface IConvertible { // Summary: // Returns the System.TypeCode for this instance. // // Returns: // The enumerated constant that is the System.TypeCode of the class or value // type that implements this interface. [Pure][Reads(ReadsAttribute.Reads.Owned)] TypeCode GetTypeCode(); // // Summary: // Converts the value of this instance to an equivalent Boolean value using // the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A Boolean value equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] bool ToBoolean(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 8-bit unsigned integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 8-bit unsigned integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] byte ToByte(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent Unicode character using // the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A Unicode character equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] char ToChar(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent System.DateTime using // the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A System.DateTime instance equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] DateTime ToDateTime(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent System.Decimal number // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A System.Decimal number equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] decimal ToDecimal(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent double-precision floating-point // number using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A double-precision floating-point number equivalent to the value of this // instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] double ToDouble(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 16-bit signed integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 16-bit signed integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] short ToInt16(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 32-bit signed integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 32-bit signed integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] int ToInt32(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 64-bit signed integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 64-bit signed integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] long ToInt64(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 8-bit signed integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 8-bit signed integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] sbyte ToSByte(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent single-precision floating-point // number using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A single-precision floating-point number equivalent to the value of this // instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] float ToSingle(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent System.String using // the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // A System.String instance equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] string ToString(IFormatProvider provider); // // Summary: // Converts the value of this instance to an System.Object of the specified // System.Type that has an equivalent value, using the specified culture-specific // formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // conversionType: // The System.Type to which the value of this instance is converted. // // Returns: // An System.Object instance of type conversionType whose value is equivalent // to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] object ToType(Type conversionType, IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 16-bit unsigned integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 16-bit unsigned integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] ushort ToUInt16(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 32-bit unsigned integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 32-bit unsigned integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] uint ToUInt32(IFormatProvider provider); // // Summary: // Converts the value of this instance to an equivalent 64-bit unsigned integer // using the specified culture-specific formatting information. // // Parameters: // provider: // An System.IFormatProvider interface implementation that supplies culture-specific // formatting information. // // Returns: // An 64-bit unsigned integer equivalent to the value of this instance. [Pure][Reads(ReadsAttribute.Reads.Owned)] ulong ToUInt64(IFormatProvider provider); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Xml; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// Project-related Xml utilities /// </summary> internal class ProjectXmlUtilities { /// <summary> /// Gets child elements, ignoring whitespace and comments. /// </summary> /// <exception cref="InvalidProjectFileException">Thrown for elements in the wrong namespace, or unexpected XML node types</exception> internal static List<XmlElement> GetValidChildElements(XmlElement element) { List<XmlElement> children = new List<XmlElement>(); foreach (XmlNode child in element) { switch (child.NodeType) { case XmlNodeType.Comment: case XmlNodeType.Whitespace: // These are legal, and ignored break; case XmlNodeType.Element: XmlElement childElement = (XmlElement)child; VerifyThrowProjectValidNamespace(childElement); children.Add(childElement); break; default: ThrowProjectInvalidChildElement(child); break; } } return children; } /// <summary> /// Throw an invalid project exception if the child is not an XmlElement /// </summary> /// <param name="childNode"></param> internal static void VerifyThrowProjectXmlElementChild(XmlNode childNode) { if (childNode.NodeType != XmlNodeType.Element) { ThrowProjectInvalidChildElement(childNode); } } /// <summary> /// Throw an invalid project exception if there are any child elements at all /// </summary> internal static void VerifyThrowProjectNoChildElements(XmlElement element) { List<XmlElement> childElements = GetValidChildElements(element); if (childElements.Count > 0) { ThrowProjectInvalidChildElement(element.FirstChild); } } /// <summary> /// Throw an invalid project exception indicating that the child is not valid beneath the element /// </summary> internal static void ThrowProjectInvalidChildElement(XmlNode child) { ProjectErrorUtilities.ThrowInvalidProject(child, "UnrecognizedChildElement", child.Name, child.ParentNode.Name); } /// <summary> /// Throws an InternalErrorException if the name of the element is not the expected name. /// </summary> internal static void VerifyThrowElementName(XmlElement element, string expected) { ErrorUtilities.VerifyThrowNoAssert(String.Equals(element.Name, expected, StringComparison.Ordinal), "Expected " + expected + " element, got " + element.Name); } /// <summary> /// Verifies an element has a valid name, and is in the MSBuild namespace, otherwise throws an InvalidProjectFileException. /// </summary> internal static void VerifyThrowProjectValidNameAndNamespace(XmlElement element) { XmlUtilities.VerifyThrowProjectValidElementName(element); VerifyThrowProjectValidNamespace(element); } /// <summary> /// Verifies that an element is in the MSBuild namespace, otherwise throws an InvalidProjectFileException. /// </summary> internal static void VerifyThrowProjectValidNamespace(XmlElement element) { if (element.Prefix.Length > 0 || !String.Equals(element.NamespaceURI, XMakeAttributes.defaultXmlNamespace, StringComparison.OrdinalIgnoreCase)) { ProjectErrorUtilities.ThrowInvalidProject(element, "CustomNamespaceNotAllowedOnThisChildElement", element.Name, element.ParentNode.Name); } } /// <summary> /// If there are any attributes on the element, throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// </summary> internal static void VerifyThrowProjectNoAttributes(XmlElement element) { foreach(XmlAttribute attribute in element.Attributes) { ThrowProjectInvalidAttribute(attribute); } } /// <summary> /// If the condition is false, throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// </summary> internal static void VerifyThrowProjectInvalidAttribute(bool condition, XmlAttribute attribute) { if (!condition) { ThrowProjectInvalidAttribute(attribute); } } /// <summary> /// Throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// </summary> internal static void ThrowProjectInvalidAttribute(XmlAttribute attribute) { ProjectErrorUtilities.ThrowInvalidProject(attribute, "UnrecognizedAttribute", attribute.Name, attribute.OwnerElement.Name); } /// <summary> /// Get the Condition attribute, if any. Optionally, throw an invalid project exception if there are /// any other attributes. /// </summary> internal static XmlAttribute GetConditionAttribute(XmlElement element, bool verifySoleAttribute) { XmlAttribute condition = null; foreach (XmlAttribute attribute in element.Attributes) { switch (attribute.Name) { case XMakeAttributes.condition: condition = attribute; break; // Label is only recognized by the new OM. // Ignore BUT ONLY if the caller of this function is a // PropertyGroup, ItemDefinitionGroup, or ItemGroup: the "Label" // attribute is only legal on those element types. case XMakeAttributes.label: if (!( String.Equals(element.Name, XMakeElements.propertyGroup, StringComparison.Ordinal) || String.Equals(element.Name, XMakeElements.itemDefinitionGroup, StringComparison.Ordinal) || String.Equals(element.Name, XMakeElements.itemGroup, StringComparison.Ordinal) )) { ProjectErrorUtilities.VerifyThrowInvalidProject(!verifySoleAttribute, attribute, "UnrecognizedAttribute", attribute.Name, element.Name); } // otherwise, do nothing. break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(!verifySoleAttribute, attribute, "UnrecognizedAttribute", attribute.Name, element.Name); break; } } return condition; } /// <summary> /// Sets the value of an attribute, but if the value to set is null or empty, just /// removes the element. Returns the attribute, or null if it was removed. /// </summary> internal static XmlAttribute SetOrRemoveAttribute(XmlElement element, string name, string value) { if (String.IsNullOrEmpty(value)) { // The caller passed in a null or an empty value. So remove the attribute. element.RemoveAttribute(name); return null; } else { // Set the new attribute value element.SetAttribute(name, value); XmlAttribute attribute = element.Attributes[name]; return attribute; } } /// <summary> /// Returns the value of the attribute. /// If the attribute is null, returns an empty string. /// </summary> internal static string GetAttributeValue(XmlAttribute attribute) { return (attribute == null) ? String.Empty : attribute.Value; } } }
/* * 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; namespace QuantConnect.Data.Market { /// <summary> /// QuoteBar class for second and minute resolution data: /// An OHLC implementation of the QuantConnect BaseData class with parameters for candles. /// </summary> public class QuoteBar : BaseData, IBar { // scale factor used in QC equity/forex data files private const decimal _scaleFactor = 10000m; private int _updateBidCount = 0; private long _sumBidSize = 0; private int _updateAskCount = 0; private long _sumAskSize = 0; /// <summary> /// Average bid size /// </summary> public long AvgBidSize { get; set; } /// <summary> /// Average ask size /// </summary> public long AvgAskSize { get; set; } /// <summary> /// Bid OHLC /// </summary> public Bar Bid { get; set; } /// <summary> /// Ask OHLC /// </summary> public Bar Ask { get; set; } /// <summary> /// Opening price of the bar: Defined as the price at the start of the time period. /// </summary> public decimal Open { get { if (Bid != null && Ask != null) { return (Bid.Open + Ask.Open) / 2m; } if (Bid != null) { return Bid.Open; } if (Ask != null) { return Ask.Open; } return 0m; } } /// <summary> /// High price of the QuoteBar during the time period. /// </summary> public decimal High { get { if (Bid != null && Ask != null) { return (Bid.High + Ask.High) / 2m; } if (Bid != null) { return Bid.High; } if (Ask != null) { return Ask.High; } return 0m; } } /// <summary> /// Low price of the QuoteBar during the time period. /// </summary> public decimal Low { get { if (Bid != null && Ask != null) { return (Bid.Low + Ask.Low) / 2m; } if (Bid != null) { return Bid.Low; } if (Ask != null) { return Ask.Low; } return 0m; } } /// <summary> /// Closing price of the QuoteBar. Defined as the price at Start Time + TimeSpan. /// </summary> public decimal Close { get { if (Bid != null && Ask != null) { return (Bid.Close + Ask.Close) / 2m; } if (Bid != null) { return Bid.Close; } if (Ask != null) { return Ask.Close; } return Value; } } /// <summary> /// The closing time of this bar, computed via the Time and Period /// </summary> public override DateTime EndTime { get { return Time + Period; } set { Period = value - Time; } } /// <summary> /// The period of this quote bar, (second, minute, daily, ect...) /// </summary> public TimeSpan Period { get; set; } /// <summary> /// Default initializer to setup an empty quotebar. /// </summary> public QuoteBar() { Symbol = Symbol.Empty; Time = new DateTime(); Bid = new Bar(); Ask = new Bar(); AvgBidSize = _sumBidSize = 0; AvgAskSize = _sumAskSize = 0; Value = 0; Period = TimeSpan.FromMinutes(1); DataType = MarketDataType.QuoteBar; _updateBidCount = 0; _updateAskCount = 0; } /// <summary> /// Cloner constructor for implementing fill forward. /// Return a new instance with the same values as this original. /// </summary> /// <param name="original">Original quotebar object we seek to clone</param> public QuoteBar(QuoteBar original) { Symbol = original.Symbol; Time = new DateTime(original.Time.Ticks); var bid = original.Bid; Bid = bid == null ? null : new Bar(bid.Open, bid.High, bid.Low, bid.Close); var ask = original.Ask; Ask = ask == null ? null : new Bar(ask.Open, ask.High, ask.Low, ask.Close); AvgBidSize = original.AvgBidSize; AvgAskSize = original.AvgAskSize; Value = original.Close; Period = original.Period; DataType = MarketDataType.QuoteBar; _updateBidCount = 0; _updateAskCount = 0; } /// <summary> /// Initialize Quote Bar with Bid(OHLC) and Ask(OHLC) Values: /// </summary> /// <param name="time">DateTime Timestamp of the bar</param> /// <param name="symbol">Market MarketType Symbol</param> /// <param name="bid">Bid OLHC bar</param> /// <param name="avgBidSize">Average bid size over period</param> /// <param name="ask">Ask OLHC bar</param> /// <param name="avgAskSize">Average ask size over period</param> /// <param name="period">The period of this bar, specify null for default of 1 minute</param> public QuoteBar(DateTime time, Symbol symbol, IBar bid, long avgBidSize, IBar ask, long avgAskSize, TimeSpan? period = null) { Symbol = symbol; Time = time; Bid = bid == null ? new Bar() : new Bar(bid.Open, bid.High, bid.Low, bid.Close); Ask = ask == null ? new Bar() : new Bar(ask.Open, ask.High, ask.Low, ask.Close); AvgBidSize = avgBidSize; AvgAskSize = avgAskSize; Value = Close; Period = period ?? TimeSpan.FromMinutes(1); DataType = MarketDataType.QuoteBar; _updateBidCount = 0; _updateAskCount = 0; } /// <summary> /// Update the quotebar - build the bar from this pricing information: /// </summary> /// <param name="lastTrade">The last trade price</param> /// <param name="bidPrice">Current bid price</param> /// <param name="askPrice">Current asking price</param> /// <param name="volume">Volume of this trade</param> /// <param name="bidSize">The size of the current bid, if available, if not, pass 0</param> /// <param name="askSize">The size of the current ask, if available, if not, pass 0</param> public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize) { // update our bid and ask bars Bid.Update(bidPrice); Ask.Update(askPrice); if ((_updateBidCount == 0 && AvgBidSize > 0) || (_updateAskCount == 0 && AvgAskSize > 0)) { throw new InvalidOperationException("Average bid/ask size cannot be greater then zero if update counter is zero."); } if (bidSize > 0) { _updateBidCount++; _sumBidSize += Convert.ToInt32(bidSize); AvgBidSize = _sumBidSize / _updateBidCount; } if (askSize > 0) { _updateAskCount++; _sumAskSize += Convert.ToInt32(askSize); AvgAskSize = _sumAskSize / _updateAskCount; } // be prepared for updates without trades if (lastTrade != 0) Value = lastTrade; else if (askPrice != 0) Value = askPrice; else if (bidPrice != 0) Value = bidPrice; } /// <summary> /// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine. /// </summary> /// <param name="config">Symbols, Resolution, DataType, </param> /// <param name="line">Line from the data file requested</param> /// <param name="date">Date of this reader request</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Enumerable iterator for returning each line of the required data.</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { throw new NotImplementedException("Equity quote bars data format has not yet been finalized."); } /// <summary> /// Get Source for Custom Data File /// >> What source file location would you prefer for each type of usage: /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source request if source spread across multiple files</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>String source location of the file</returns> public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { // we have a design in github for options structure: https://github.com/QuantConnect/Lean/issues/166 throw new NotImplementedException("QuoteBar folder structure has not been implemented yet."); } /// <summary> /// Return a new instance clone of this quote bar, used in fill forward /// </summary> /// <returns>A clone of the current quote bar</returns> public override BaseData Clone() { return new QuoteBar { Ask = Ask == null ? null : Ask.Clone(), Bid = Bid == null ? null : Bid.Clone(), AvgAskSize = AvgAskSize, AvgBidSize = AvgBidSize, Symbol = Symbol, Time = Time, Period = Period, Value = Value, DataType = DataType }; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Compute.Tests { public class VMScaleSetNetworkProfileTests : VMScaleSetTestsBase { /// <summary> /// Associates a VMScaleSet to an Application gateway /// </summary> [Fact] public void TestVMScaleSetWithApplciationGateway() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var gatewaySubnet = vnetResponse.Subnets[0]; var vmssSubnet = vnetResponse.Subnets[1]; ApplicationGateway appgw = CreateApplicationGateway(rgName, gatewaySubnet); Microsoft.Azure.Management.Compute.Models.SubResource backendAddressPool = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = appgw.BackendAddressPools[0].Id }; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations[0] .ApplicationGatewayBackendAddressPools.Add(backendAddressPool), createWithPublicIpAddress: false, subnet: vmssSubnet); var getGwResponse = m_NrpClient.ApplicationGateways.Get(rgName, appgw.Name); Assert.True(2 == getGwResponse.BackendAddressPools[0].BackendIPConfigurations.Count); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with DnsSettings /// </summary> [Fact] public void TestVMScaleSetWithDnsSettings() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var nicDnsSettings = new VirtualMachineScaleSetNetworkConfigurationDnsSettings(); nicDnsSettings.DnsServers = new List<string>() { "10.0.0.5", "10.0.0.6" }; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].DnsSettings = nicDnsSettings, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers); Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers.Count); Assert.Contains(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers, ip => string.Equals("10.0.0.5", ip)); Assert.Contains(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers, ip => string.Equals("10.0.0.6", ip)); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with PublicIp /// </summary> [Fact] public void TestVMScaleSetWithPublicIP() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); var dnsname = TestUtilities.GenerateName("dnsname"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { // Hard code the location to "westcentralus". // This is because NRP is still deploying to other regions and is not available worldwide. // Before changing the default location, we have to save it to be reset it at the end of the test. // Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset. Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration(); publicipConfiguration.Name = "pip1"; publicipConfiguration.IdleTimeoutInMinutes = 10; publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings(); publicipConfiguration.DnsSettings.DomainNameLabel = dnsname; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration); Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name); Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings); Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with PublicIp with Ip tags /// </summary> [Fact] public void TestVMScaleSetWithPublicIPAndIPTags() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); var dnsname = TestUtilities.GenerateName("dnsname"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { // Hard code the location to "westcentralus". // This is because NRP is still deploying to other regions and is not available worldwide. // Before changing the default location, we have to save it to be reset it at the end of the test. // Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset. Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration(); publicipConfiguration.Name = "pip1"; publicipConfiguration.IdleTimeoutInMinutes = 10; publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings(); publicipConfiguration.DnsSettings.DomainNameLabel = dnsname; publicipConfiguration.IpTags = new List<VirtualMachineScaleSetIpTag> { new VirtualMachineScaleSetIpTag("FirstPartyUsage", "/Sql") }; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration); Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name); Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings); Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags); Assert.Equal("FirstPartyUsage", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags[0].IpTagType); Assert.Equal("/Sql", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags[0].Tag); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with PublicIp with Ip prefix /// </summary> [Fact] public void TestVMScaleSetWithPublicIPAndPublicIPPrefix() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); if (originalTestLocation == null) { originalTestLocation = String.Empty; } // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); var dnsname = TestUtilities.GenerateName("dnsname"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var publicIpPrefix = CreatePublicIPPrefix(rgName, 30); var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration(); publicipConfiguration.Name = "pip1"; publicipConfiguration.IdleTimeoutInMinutes = 10; publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings(); publicipConfiguration.DnsSettings.DomainNameLabel = dnsname; publicipConfiguration.PublicIPPrefix = new Microsoft.Azure.Management.Compute.Models.SubResource(); publicipConfiguration.PublicIPPrefix.Id = publicIpPrefix.Id; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration); Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name); Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings); Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel); Assert.Equal(publicIpPrefix.Id, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.PublicIPPrefix.Id); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with Nsg /// </summary> [Fact] public void TestVMScaleSetWithnNsg() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); var dnsname = TestUtilities.GenerateName("dnsname"); var nsgname = TestUtilities.GenerateName("nsg"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var nsg = CreateNsg(rgName, nsgname); Microsoft.Azure.Management.Compute.Models.SubResource nsgId = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = nsg.Id }; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].NetworkSecurityGroup = nsgId, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].NetworkSecurityGroup); Assert.Equal(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].NetworkSecurityGroup.Id, nsg.Id, StringComparer.OrdinalIgnoreCase); var getNsgResponse = m_NrpClient.NetworkSecurityGroups.Get(rgName, nsg.Name); Assert.Equal(2, getNsgResponse.NetworkInterfaces.Count); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with ipv6 /// </summary> [Fact] public void TestVMScaleSetWithnIpv6() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); var dnsname = TestUtilities.GenerateName("dnsname"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var ipv6ipconfig = new VirtualMachineScaleSetIPConfiguration(); ipv6ipconfig.Name = "ipv6"; ipv6ipconfig.PrivateIPAddressVersion = Microsoft.Azure.Management.Compute.Models.IPVersion.IPv6; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => { virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations[0].PrivateIPAddressVersion = Microsoft.Azure.Management.Compute.Models.IPVersion.IPv4; virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile .NetworkInterfaceConfigurations[0].IpConfigurations.Add(ipv6ipconfig); }, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with multiple IPConfigurations on a single NIC /// </summary> [Fact] public void TestVMSSWithMultiCA() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; var secondaryCA = new VirtualMachineScaleSetIPConfiguration( name: TestUtilities.GenerateName("vmsstestnetconfig"), subnet: new ApiEntityReference() { Id = vmssSubnet.Id }); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => { virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].Primary = true; virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Add(secondaryCA); }, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count); Assert.True(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count(ip => ip.Primary == true) == 1); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Associates a VMScaleSet with a NIC that has accelerated networking enabled. /// </summary> [Fact] public void TestVMSSAccelNtwkng() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rgName = TestUtilities.GenerateName(TestPrefix) + 1; var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vnetResponse = CreateVNETWithSubnets(rgName, 2); var vmssSubnet = vnetResponse.Subnets[1]; VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName: rgName, vmssName: vmssName, storageAccount: storageAccountOutput, imageRef: imageRef, inputVMScaleSet: out inputVMScaleSet, vmScaleSetCustomizer: (virtualMachineScaleSet) => { virtualMachineScaleSet.Sku.Name = VirtualMachineSizeTypes.StandardDS11V2; virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].EnableAcceleratedNetworking = true; }, createWithPublicIpAddress: false, subnet: vmssSubnet); var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.True(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].EnableAcceleratedNetworking == true); passed = true; } finally { m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace CoursesAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// UsersResponse /// </summary> [DataContract] public partial class UsersResponse : IEquatable<UsersResponse>, IValidatableObject { public UsersResponse() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="UsersResponse" /> class. /// </summary> /// <param name="EndPosition">The last position in the result set. .</param> /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param> /// <param name="PreviousUri">The postal code for the billing address..</param> /// <param name="ResultSetSize">The number of results returned in this response. .</param> /// <param name="StartPosition">Starting position of the current result set..</param> /// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param> /// <param name="Users">Users.</param> public UsersResponse(string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string), List<UserInfo> Users = default(List<UserInfo>)) { this.EndPosition = EndPosition; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.ResultSetSize = ResultSetSize; this.StartPosition = StartPosition; this.TotalSetSize = TotalSetSize; this.Users = Users; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set. </value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response. </value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response. /// </summary> /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value> [DataMember(Name="totalSetSize", EmitDefaultValue=false)] public string TotalSetSize { get; set; } /// <summary> /// Gets or Sets Users /// </summary> [DataMember(Name="users", EmitDefaultValue=false)] public List<UserInfo> Users { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UsersResponse {\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n"); sb.Append(" Users: ").Append(Users).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as UsersResponse); } /// <summary> /// Returns true if UsersResponse instances are equal /// </summary> /// <param name="other">Instance of UsersResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(UsersResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.TotalSetSize == other.TotalSetSize || this.TotalSetSize != null && this.TotalSetSize.Equals(other.TotalSetSize) ) && ( this.Users == other.Users || this.Users != null && this.Users.SequenceEqual(other.Users) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.EndPosition != null) hash = hash * 59 + this.EndPosition.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 59 + this.ResultSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 59 + this.StartPosition.GetHashCode(); if (this.TotalSetSize != null) hash = hash * 59 + this.TotalSetSize.GetHashCode(); if (this.Users != null) hash = hash * 59 + this.Users.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace BellTowerEscape.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { /// <summary> /// Tests that apply to the filesystem/cache portions of the X509 infrastructure on Unix implementations. /// </summary> [Collection("X509Filesystem")] public static class X509FilesystemTests { // #9293: Our Fedora23 CI machines use NTFS for "tmphome", which causes our filesystem permissions checks to fail. private static bool IsReliableInCI { get; } = !PlatformDetection.IsFedora23 && !PlatformDetection.IsUbuntu1610; [Fact] [OuterLoop] public static void VerifyCrlCache() { string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls"); string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename); Directory.CreateDirectory(crlDirectory); File.Delete(crlFile); using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var unrelated = new X509Certificate2(TestData.DssCer)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(unrelated); chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); // The very start of the CRL period. chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly; chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority; bool valid = chain.Build(microsoftDotComIssuer); Assert.True(valid, "Precondition: Chain builds with no revocation checks"); int initialErrorCount = chain.ChainStatus.Length; Assert.InRange(initialErrorCount, 0, 1); if (initialErrorCount > 0) { Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status); } chainHolder.DisposeChainElements(); chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; valid = chain.Build(microsoftDotComIssuer); Assert.False(valid, "Chain should not build validly"); Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length); Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status); File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII); chainHolder.DisposeChainElements(); valid = chain.Build(microsoftDotComIssuer); Assert.True(valid, "Chain should build validly now"); Assert.Equal(initialErrorCount, chain.ChainStatus.Length); } } [Fact] public static void X509Store_OpenExisting_Fails() { RunX509StoreTest( (store, storeDirectory) => { // Since the directory was explicitly deleted already, this should fail. Assert.Throws<CryptographicException>( () => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly)); }); } [Fact] private static void X509Store_AddReadOnly() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); // Adding a certificate when the store is ReadOnly should fail: Assert.Throws<CryptographicException>(() => store.Add(cert)); // Since we haven't done anything yet, we shouldn't have polluted the hard drive. Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); } }); } [Fact] private static void X509Store_AddClosed() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) { // Adding a certificate when the store is closed should fail: Assert.Throws<CryptographicException>(() => store.Add(cert)); // Since we haven't done anything yet, we shouldn't have polluted the hard drive. Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddOne() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); store.Add(cert); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(1, Directory.GetFiles(storeDirectory).Length); using (var coll = new ImportedCollection(store.Certificates)) { X509Certificate2Collection storeCerts = coll.Collection; Assert.Equal(1, storeCerts.Count); using (X509Certificate2 storeCert = storeCerts[0]) { Assert.Equal(cert, storeCert); Assert.NotSame(cert, storeCert); } } } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddOneAfterUpgrade() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); // Adding a certificate when the store is ReadOnly should fail: Assert.Throws<CryptographicException>(() => store.Add(cert)); // Since we haven't done anything yet, we shouldn't have polluted the hard drive. Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); // Calling Open on an open store changes the access rights: store.Open(OpenFlags.ReadWrite); store.Add(cert); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(1, Directory.GetFiles(storeDirectory).Length); using (var coll = new ImportedCollection(store.Certificates)) { X509Certificate2Collection storeCerts = coll.Collection; Assert.Equal(1, storeCerts.Count); using (X509Certificate2 storeCert = storeCerts[0]) { Assert.Equal(cert, storeCert); Assert.NotSame(cert, storeCert); } } } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_DowngradePermissions() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); // Ensure that ReadWrite took effect. store.Add(certA); store.Open(OpenFlags.ReadOnly); // Adding a certificate when the store is ReadOnly should fail: Assert.Throws<CryptographicException>(() => store.Add(certB)); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddAfterDispose() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); // Dispose returns the store to the pre-opened state. store.Dispose(); // Adding a certificate when the store is closed should fail: Assert.Throws<CryptographicException>(() => store.Add(certB)); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddAndClear() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); store.Add(cert); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(1, Directory.GetFiles(storeDirectory).Length); store.Remove(cert); // The directory should still exist. Assert.True(Directory.Exists(storeDirectory), "Store Directory Still Exists"); Assert.Equal(0, Directory.GetFiles(storeDirectory).Length); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddDuplicate() { RunX509StoreTest( (store, storeDirectory) => { using (var cert = new X509Certificate2(TestData.MsCertificate)) using (var certClone = new X509Certificate2(cert.RawData)) { store.Open(OpenFlags.ReadWrite); store.Add(cert); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(1, Directory.GetFiles(storeDirectory).Length); store.Add(certClone); Assert.Equal(1, Directory.GetFiles(storeDirectory).Length); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddTwo() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); store.Add(certB); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(2, Directory.GetFiles(storeDirectory).Length); X509Certificate2Collection storeCerts = store.Certificates; Assert.Equal(2, storeCerts.Count); X509Certificate2[] expectedCerts = { certA, certB }; foreach (X509Certificate2 storeCert in storeCerts) { Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddTwo_UpgradePrivateKey() { RunX509StoreTest( (store, storeDirectory) => { using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (var certAPublic = new X509Certificate2(certAPrivate.RawData)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); store.Add(certAPublic); store.Add(certB); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); string[] storeFiles = Directory.GetFiles(storeDirectory); Assert.Equal(2, storeFiles.Length); X509Certificate2Collection storeCerts = store.Certificates; Assert.Equal(2, storeCerts.Count); X509Certificate2[] expectedCerts = { certAPublic, certB }; foreach (X509Certificate2 storeCert in storeCerts) { Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)"); storeCert.Dispose(); } store.Add(certAPrivate); // It replaces the existing file, the names should be unaffected. Assert.Equal(storeFiles, Directory.GetFiles(storeDirectory)); storeCerts = store.Certificates; Assert.Equal(2, storeCerts.Count); bool foundCertA = false; foreach (X509Certificate2 storeCert in storeCerts) { // The public instance and private instance are .Equal if (storeCert.Equals(certAPublic)) { Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)"); foundCertA = true; } else { Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)"); } Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } Assert.True(foundCertA, "foundCertA"); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_AddTwo_UpgradePrivateKey_NoDowngrade() { RunX509StoreTest( (store, storeDirectory) => { using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (var certAPublic = new X509Certificate2(certAPrivate.RawData)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); store.Add(certAPublic); store.Add(certB); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); X509Certificate2Collection storeCerts = store.Certificates; Assert.Equal(2, storeCerts.Count); X509Certificate2[] expectedCerts = { certAPublic, certB }; foreach (X509Certificate2 storeCert in storeCerts) { Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)"); Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } // Add the private (checked in X509Store_AddTwo_UpgradePrivateKey) store.Add(certAPrivate); // Then add the public again, which shouldn't do anything. store.Add(certAPublic); storeCerts = store.Certificates; Assert.Equal(2, storeCerts.Count); bool foundCertA = false; foreach (X509Certificate2 storeCert in storeCerts) { if (storeCert.Equals(certAPublic)) { Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)"); foundCertA = true; } else { Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)"); } Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } Assert.True(foundCertA, "foundCertA"); } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_DistinctCollections() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); store.Add(certB); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(2, Directory.GetFiles(storeDirectory).Length); X509Certificate2Collection storeCertsA = store.Certificates; X509Certificate2Collection storeCertsB = store.Certificates; Assert.NotSame(storeCertsA, storeCertsB); Assert.Equal(storeCertsA.Count, storeCertsB.Count); foreach (X509Certificate2 collACert in storeCertsA) { int bIndex = storeCertsB.IndexOf(collACert); Assert.InRange(bIndex, 0, storeCertsB.Count); X509Certificate2 collBCert = storeCertsB[bIndex]; // Equal is implied by IndexOf working. Assert.NotSame(collACert, collBCert); storeCertsB.RemoveAt(bIndex); collACert.Dispose(); collBCert.Dispose(); } } }); } [ConditionalFact(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] private static void X509Store_Add4_Remove1() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) using (var certBClone = new X509Certificate2(certB.RawData)) using (var certC = new X509Certificate2(TestData.ECDsa256Certificate)) using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); store.Add(certB); store.Add(certC); store.Add(certD); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); Assert.Equal(4, Directory.GetFiles(storeDirectory).Length); X509Certificate2[] expectedCerts = { certA, certB, certC, certD }; X509Certificate2Collection storeCerts = store.Certificates; Assert.Equal(4, storeCerts.Count); foreach (X509Certificate2 storeCert in storeCerts) { Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } store.Remove(certBClone); Assert.Equal(3, Directory.GetFiles(storeDirectory).Length); expectedCerts = new[] { certA, certC, certD }; storeCerts = store.Certificates; Assert.Equal(3, storeCerts.Count); foreach (X509Certificate2 storeCert in storeCerts) { Assert.Contains(storeCert, expectedCerts); storeCert.Dispose(); } } }); } [ConditionalTheory(nameof(IsReliableInCI))] [OuterLoop(/* Alters user/machine state */)] [InlineData(false)] [InlineData(true)] private static void X509Store_MultipleObjects(bool matchCase) { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) using (var certB = new X509Certificate2(TestData.DssCer)) using (var certC = new X509Certificate2(TestData.ECDsa256Certificate)) using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); store.Add(certB); Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)"); string newName = store.Name; if (!matchCase) { newName = newName.ToUpperInvariant(); Assert.NotEqual(store.Name, newName); } using (X509Store storeClone = new X509Store(newName, store.Location)) { storeClone.Open(OpenFlags.ReadWrite); AssertEqualContents(store, storeClone); store.Add(certC); // The object was added to store, but should show up in both objects // after re-reading the Certificates property AssertEqualContents(store, storeClone); // Now add one to storeClone to prove bidirectionality. storeClone.Add(certD); AssertEqualContents(store, storeClone); } } }); } [Fact] [OuterLoop( /* Alters user/machine state */)] private static void X509Store_FiltersDuplicateOnLoad() { RunX509StoreTest( (store, storeDirectory) => { using (var certA = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); store.Add(certA); // Emulate a race condition of parallel adds with the following flow // AdderA: Notice [thumbprint].pfx is available, create it (0 bytes) // AdderB: Notice [thumbprint].pfx already exists, but can't be read, move to [thumbprint].1.pfx // AdderA: finish write // AdderB: finish write string[] files = Directory.GetFiles(storeDirectory, "*.pfx"); Assert.Equal(1, files.Length); string srcFile = files[0]; string baseName = Path.GetFileNameWithoutExtension(srcFile); string destFile = Path.Combine(storeDirectory, srcFile + ".1.pfx"); File.Copy(srcFile, destFile); using (var coll = new ImportedCollection(store.Certificates)) { Assert.Equal(1, coll.Collection.Count); Assert.Equal(certA, coll.Collection[0]); } // Also check that remove removes both files. store.Remove(certA); string[] filesAfter = Directory.GetFiles(storeDirectory, "*.pfx"); Assert.Equal(0, filesAfter.Length); } }); } private static void AssertEqualContents(X509Store storeA, X509Store storeB) { Assert.NotSame(storeA, storeB); using (var storeATracker = new ImportedCollection(storeA.Certificates)) using (var storeBTracker = new ImportedCollection(storeB.Certificates)) { X509Certificate2Collection storeACerts = storeATracker.Collection; X509Certificate2Collection storeBCerts = storeBTracker.Collection; Assert.Equal(storeACerts.OfType<X509Certificate2>(), storeBCerts.OfType<X509Certificate2>()); } } private static void RunX509StoreTest(Action<X509Store, string> testAction) { string certStoresFeaturePath = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores"); string storeName = "TestStore" + Guid.NewGuid().ToString("N"); string storeDirectory = Path.Combine(certStoresFeaturePath, storeName.ToLowerInvariant()); if (Directory.Exists(storeDirectory)) { Directory.Delete(storeDirectory, true); } try { using (X509Store store = new X509Store(storeName, StoreLocation.CurrentUser)) { testAction(store, storeDirectory); } } finally { try { if (Directory.Exists(storeDirectory)) { Directory.Delete(storeDirectory, true); } } catch { // Don't allow any (additional?) I/O errors to propagate. } } } // `openssl crl -in [MicrosoftDotComRootCrlPem] -noout -hash`.crl private const string MicrosoftDotComRootCrlFilename = "b204d74a.crl"; // This CRL was downloaded 2015-08-31 20:31 PDT // It is valid from Jun 17 00:00:00 2015 GMT to Sep 30 23:59:59 2015 GMT private const string MicrosoftDotComRootCrlPem = @"-----BEGIN X509 CRL----- MIICETCB+jANBgkqhkiG9w0BAQUFADCByjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT DlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3Jr MTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp emVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQ cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUXDTE1MDYxNzAwMDAw MFoXDTE1MDkzMDIzNTk1OVowDQYJKoZIhvcNAQEFBQADggEBAFxqobObEqKNSAe+ A9cHCYI7sw+Vc8HuE7E+VZc6ni3a2UHiprYuXDsvD18+cyv/nFSLpLqLmExZrsf/ dzH8GH2HgBTt5aO/nX08EBrDgcjHo9b0VI6ZuOOaEeS0NsRh28Jupfn1Xwcsbdw9 nVh1OaExpHwxgg7pJr4pXzaAjbl3b4QfCPyTd5aaOQOEmqvJtRrMwCna4qQ3p4r6 QYe19/pXqK9my7lSmH1vZ0CmNvQeNPmnx+YmFXYTBgap+Xi2cs6GX/qI04CDzjWi sm6L0+S1Zx2wMhiYOi0JvrRizf+rIyKkDbPMoYEyXZqcCwSnv6mJQY81vmKRKU5N WKo2mLw= -----END X509 CRL-----"; } }
//---------------------------------------------------------------------------------------- // // <copyright file="CompilerState.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // An internal class which handles compiler information cache. It can read // write the cache file, this is for incremental build support. // // History: // // 11/21/05: weibz Created // //--------------------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Text; using System.Globalization; using Microsoft.Build.Tasks.Windows; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; namespace MS.Internal.Tasks { // // Only cache information for below types. // internal enum CompilerStateType : int { AssemblyName = 0x00, AssemblyVersion, AssemblyPublicKeyToken, OutputType, Language, LanguageSourceExtension, OutputPath, RootNamespace, LocalizationDirectivesToLocFile, HostInBrowser, DefineConstants, ApplicationFile, PageMarkup, ContentFiles, SourceCodeFiles, References, PageMarkupFileNames, SplashImage, Pass2Required, MaxCount, } // <summary> // CompilerState // </summary> internal class CompilerState { // <summary> // ctor of CompilerState // </summary> internal CompilerState(string stateFilePath, ITaskFileService taskFileService) { _cacheInfoList = new String[(int)CompilerStateType.MaxCount]; _stateFilePath = stateFilePath; _taskFileService = taskFileService; } #region internal methods // <summary> // Detect whether the state file exists or not. // </summary> // <returns></returns> internal bool StateFileExists() { return _taskFileService.Exists(_stateFilePath); } // // Clean up the state file. // internal void CleanupCache() { if (StateFileExists() ) { _taskFileService.Delete(_stateFilePath); } } internal bool SaveStateInformation(MarkupCompilePass1 mcPass1) { Debug.Assert(String.IsNullOrEmpty(_stateFilePath) != true, "StateFilePath must not be empty."); Debug.Assert(mcPass1 != null, "A valid instance of MarkupCompilePass1 must be passed to method SaveCacheInformation."); Debug.Assert(_cacheInfoList.Length == (int)CompilerStateType.MaxCount, "The Cache string array should be already allocated."); // Transfer the cache related information from mcPass1 to this instance. AssemblyName = mcPass1.AssemblyName; AssemblyVersion = mcPass1.AssemblyVersion; AssemblyPublicKeyToken = mcPass1.AssemblyPublicKeyToken; OutputType = mcPass1.OutputType; Language = mcPass1.Language; LanguageSourceExtension = mcPass1.LanguageSourceExtension; OutputPath = mcPass1.OutputPath; RootNamespace = mcPass1.RootNamespace; LocalizationDirectivesToLocFile = mcPass1.LocalizationDirectivesToLocFile; HostInBrowser = mcPass1.HostInBrowser; DefineConstants = mcPass1.DefineConstants; ApplicationFile = mcPass1.ApplicationFile; PageMarkup = mcPass1.PageMarkupCache; ContentFiles = mcPass1.ContentFilesCache; SourceCodeFiles = mcPass1.SourceCodeFilesCache; References = mcPass1.ReferencesCache; PageMarkupFileNames = GenerateStringFromFileNames(mcPass1.PageMarkup); SplashImage = mcPass1.SplashImageName; Pass2Required = (mcPass1.RequirePass2ForMainAssembly || mcPass1.RequirePass2ForSatelliteAssembly); return SaveStateInformation(); } internal bool SaveStateInformation() { bool bSuccess = false; // Save the cache information to the cache file. MemoryStream memStream = new MemoryStream(); // using Disposes the StreamWriter when it ends. Disposing the StreamWriter // also closes the underlying MemoryStream. Furthermore, don't add BOM here // since TaskFileService.WriteFile adds it. using (StreamWriter sw = new StreamWriter(memStream, new UTF8Encoding(false))) { for (int i =0; i<(int)CompilerStateType.MaxCount; i++) { sw.WriteLine(_cacheInfoList[i]); } sw.Flush(); _taskFileService.WriteFile(memStream.ToArray(), _stateFilePath); bSuccess = true; } return bSuccess; } // // Read the markupcompiler cache file, load the cached information // to the corresponding data fields in this class. // internal bool LoadStateInformation( ) { Debug.Assert(String.IsNullOrEmpty(_stateFilePath) != true, "_stateFilePath must be not be empty."); Debug.Assert(_cacheInfoList.Length == (int)CompilerStateType.MaxCount, "The Cache string array should be already allocated."); bool loadSuccess = false; Stream stream = null; if (_taskFileService.IsRealBuild) { // Pass2 writes to the cache, but Pass2 doesn't have a HostObject (because it's only // used for real builds), so it writes directly to the file system. So we need to read // directly from the file system; if we read via the HostFileManager, we'll get stale // results that don't reflect updates made in Pass2. stream = File.OpenRead(_stateFilePath); } else { stream = _taskFileService.GetContent(_stateFilePath); } // using Disposes the StreamReader when it ends. Disposing the StreamReader // also closes the underlying MemoryStream. Don't look for BOM at the beginning // of the stream, since we don't add it when writing. TaskFileService takes care // of this. using (StreamReader srCache = new StreamReader(stream, false)) { int i = 0; while (srCache.EndOfStream != true) { if (i >= (int)CompilerStateType.MaxCount) { break; } _cacheInfoList[i] = srCache.ReadLine(); i++; } loadSuccess = true; } return loadSuccess; } // // Generate cache string for item lists such as PageMarkup, References, // ContentFiles and CodeFiles etc. // internal static string GenerateCacheForFileList(ITaskItem[] fileItemList) { string cacheString = String.Empty; if (fileItemList != null && fileItemList.Length > 0) { int iHashCode = 0; int iCount = fileItemList.Length; for (int i = 0; i < iCount; i++) { iHashCode += fileItemList[i].ItemSpec.GetHashCode(); } StringBuilder sb = new StringBuilder(); sb.Append(iCount); sb.Append(iHashCode); cacheString = sb.ToString(); } return cacheString; } private static string GenerateStringFromFileNames(ITaskItem[] fileItemList) { string fileNames = String.Empty; if (fileItemList != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fileItemList.Length; i++) { sb.Append(fileItemList[i].ItemSpec); sb.Append(";"); } fileNames = sb.ToString(); } return fileNames; } #endregion #region internal properties internal string CacheFilePath { get { return _stateFilePath; } } internal string AssemblyName { get { return _cacheInfoList[(int)CompilerStateType.AssemblyName]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyName] = value; } } internal string AssemblyVersion { get { return _cacheInfoList[(int)CompilerStateType.AssemblyVersion]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyVersion] = value; } } internal string AssemblyPublicKeyToken { get { return _cacheInfoList[(int)CompilerStateType.AssemblyPublicKeyToken]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyPublicKeyToken] = value; } } internal string OutputType { get { return _cacheInfoList[(int)CompilerStateType.OutputType]; } set { _cacheInfoList[(int)CompilerStateType.OutputType] = value; } } internal string Language { get { return _cacheInfoList[(int)CompilerStateType.Language]; } set { _cacheInfoList[(int)CompilerStateType.Language] = value; } } internal string LanguageSourceExtension { get { return _cacheInfoList[(int)CompilerStateType.LanguageSourceExtension]; } set { _cacheInfoList[(int)CompilerStateType.LanguageSourceExtension] = value; } } internal string OutputPath { get { return _cacheInfoList[(int)CompilerStateType.OutputPath]; } set { _cacheInfoList[(int)CompilerStateType.OutputPath] = value; } } internal string RootNamespace { get { return _cacheInfoList[(int)CompilerStateType.RootNamespace]; } set { _cacheInfoList[(int)CompilerStateType.RootNamespace] = value; } } internal string LocalizationDirectivesToLocFile { get { return _cacheInfoList[(int)CompilerStateType.LocalizationDirectivesToLocFile]; } set { _cacheInfoList[(int)CompilerStateType.LocalizationDirectivesToLocFile] = value; } } internal string HostInBrowser { get { return _cacheInfoList[(int)CompilerStateType.HostInBrowser]; } set { _cacheInfoList[(int)CompilerStateType.HostInBrowser] = value; } } internal string DefineConstants { get { return _cacheInfoList[(int)CompilerStateType.DefineConstants]; } set { _cacheInfoList[(int)CompilerStateType.DefineConstants] = value; } } internal string ApplicationFile { get { return _cacheInfoList[(int)CompilerStateType.ApplicationFile]; } set { _cacheInfoList[(int)CompilerStateType.ApplicationFile] = value; } } internal string PageMarkup { get { return _cacheInfoList[(int)CompilerStateType.PageMarkup]; } set { _cacheInfoList[(int)CompilerStateType.PageMarkup] = value; } } internal string ContentFiles { get { return _cacheInfoList[(int)CompilerStateType.ContentFiles]; } set { _cacheInfoList[(int)CompilerStateType.ContentFiles] = value; } } internal string SourceCodeFiles { get { return _cacheInfoList[(int)CompilerStateType.SourceCodeFiles]; } set { _cacheInfoList[(int)CompilerStateType.SourceCodeFiles] = value; } } internal string References { get { return _cacheInfoList[(int)CompilerStateType.References]; } set { _cacheInfoList[(int)CompilerStateType.References] = value; } } internal string PageMarkupFileNames { get { return _cacheInfoList[(int)CompilerStateType.PageMarkupFileNames]; } set { _cacheInfoList[(int)CompilerStateType.PageMarkupFileNames] = value; } } internal string SplashImage { get { return _cacheInfoList[(int)CompilerStateType.SplashImage]; } set { _cacheInfoList[(int)CompilerStateType.SplashImage] = value; } } internal bool Pass2Required { get { return _cacheInfoList[(int)CompilerStateType.Pass2Required] == bool.TrueString; } set { _cacheInfoList[(int)CompilerStateType.Pass2Required] = value.ToString(CultureInfo.InvariantCulture); } } #endregion #region private data private String [] _cacheInfoList; private string _stateFilePath; private ITaskFileService _taskFileService = null; #endregion } }
#region Header /** * JsonMapper.cs * JSON to .Net object and object to JSON conversions. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; #if NETFX_CORE //using System.Reflection.IntrospectionExtensions; #endif namespace LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Helper Mehtods private static bool HasInterface(Type type, string name) { #if NETFX_CORE foreach (Type type1 in IntrospectionExtensions.GetTypeInfo(type).ImplementedInterfaces) if (type1.FullName == name) return true; return false; #else return type.GetInterface(name, true) != null; #endif } public static PropertyInfo[] GetPublicInstanceProperties(Type type) { #if NETFX_CORE List<PropertyInfo> list = new List<PropertyInfo>(); foreach (PropertyInfo propertyInfo in RuntimeReflectionExtensions.GetRuntimeProperties(type)) { if (propertyInfo.GetMethod.IsPublic && !propertyInfo.GetMethod.IsStatic) list.Add(propertyInfo); } return list.ToArray(); #else return type.GetProperties(); #endif } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (HasInterface(type, "System.Collections.IList")) data.IsList = true; foreach (PropertyInfo p_info in GetPublicInstanceProperties(type)) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (HasInterface(type, "System.Collections.IDictionary")) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in GetPublicInstanceProperties(type)) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in #if NETFX_CORE type.GetRuntimeFields() #else type.GetFields() #endif ) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in GetPublicInstanceProperties(type)) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in #if NETFX_CORE type.GetRuntimeFields() #else type.GetFields() #endif ) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = #if NETFX_CORE t1.GetRuntimeMethod ("op_Implicit", new Type[] { t2 }); #else t1.GetMethod("op_Implicit", new Type[] { t2 }); #endif lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { #if NETFX_CORE if (! inst_type.GetTypeInfo().IsClass) #else if (! inst_type.IsClass) #endif throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); #if NETFX_CORE if (inst_type.GetTypeInfo().IsAssignableFrom (json_type.GetTypeInfo())) #else if (inst_type.IsAssignableFrom(json_type)) #endif return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe it's an enum #if NETFX_CORE if (inst_type.GetTypeInfo().IsEnum) #else if (inst_type.IsEnum) #endif return Enum.ToObject (inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (inst_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { if (inst_type.FullName == "System.Object") inst_type = typeof(object[]); AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new System.Collections.ArrayList (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { if (inst_type == typeof(System.Object)) inst_type = typeof(Dictionary<string, object>); AddObjectMetadata (inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance (inst_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) { if (! reader.SkipNonMembers) { throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); } else { ReadSkip (reader); continue; } } ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void ReadSkip (JsonReader reader) { ToWrapper ( delegate { return new JsonMockWrapper (); }, reader); } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entity in (IDictionary)obj) { writer.WritePropertyName ((string) entity.Key); WriteValue (entity.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** */ public const int DfltBusywaitSleepInterval = 200; /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms512m", "-Xmx512m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// Kill Ignite processes. /// </summary> public static void KillProcesses() { IgniteProcess.KillAll(); } /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions() { IList<string> ops = new List<string>(TestJvmOpts); if (JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <returns></returns> public static string CreateTestClasspath() { return IgniteManager.CreateClasspath(forceTestClasspath: true); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout) { int left = timeout; while (true) { if (grid.Cluster.Nodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryIsEmpty(g, timeout); } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryIsEmpty(IIgnite grid, int timeout) { var handleRegistry = ((Ignite)grid).HandleRegistry; if (WaitForCondition(() => handleRegistry.Count == 0, timeout)) return; var items = handleRegistry.GetItems(); if (items.Any()) Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } } }
// TaskTreeView.cs created with MonoDevelop // User: boyd on 2/9/2008 using System; using System.Collections.Generic; using Gtk; using Mono.Unix; namespace Tasque { /// <summary> /// This is the main TreeView widget that is used to show tasks in Tasque's /// main window. /// </summary> public class TaskTreeView : Gtk.TreeView { private static Gdk.Pixbuf notePixbuf; private static Gdk.Pixbuf[] inactiveAnimPixbufs; private Gtk.TreeModelFilter modelFilter; private ICategory filterCategory; private ITask taskBeingEdited = null; private bool toggled; private static string status; static TaskTreeView () { notePixbuf = Utilities.GetIcon ("note", 16); inactiveAnimPixbufs = new Gdk.Pixbuf [12]; for (int i = 0; i < 12; i++) { string iconName = string.Format ("clock-16-{0}", i); inactiveAnimPixbufs [i] = Utilities.GetIcon (iconName, 16); } } public event EventHandler NumberOfTasksChanged; public TaskTreeView (Gtk.TreeModel model) : base () { #if GTK_2_12 // set up the timing for the tooltips this.Settings.SetLongProperty("gtk-tooltip-browse-mode-timeout", 0, "Tasque:TaskTreeView"); this.Settings.SetLongProperty("gtk-tooltip-browse-timeout", 750, "Tasque:TaskTreeView"); this.Settings.SetLongProperty("gtk-tooltip-timeout", 750, "Tasque:TaskTreeView"); ConnectEvents(); #endif // TODO: Modify the behavior of the TreeView so that it doesn't show // the highlighted row. Then, also tie in with the mouse hovering // so that as you hover the mouse around, it will automatically // select the row that the mouse is hovered over. By doing this, // we should be able to not require the user to click on a task // to select it and THEN have to click on the column item they want // to modify. filterCategory = null; modelFilter = new Gtk.TreeModelFilter (model, null); modelFilter.VisibleFunc = FilterFunc; modelFilter.RowInserted += OnRowInsertedHandler; modelFilter.RowDeleted += OnRowDeletedHandler; //Model = modelFilter Selection.Mode = Gtk.SelectionMode.Single; RulesHint = false; HeadersVisible = false; HoverSelection = true; // TODO: Figure out how to turn off selection highlight Gtk.CellRenderer renderer; // // Checkbox Column // Gtk.TreeViewColumn column = new Gtk.TreeViewColumn (); // Title for Completed/Checkbox Column column.Title = Catalog.GetString ("Completed"); column.Sizing = Gtk.TreeViewColumnSizing.Autosize; column.Resizable = false; column.Clickable = true; renderer = new Gtk.CellRendererToggle (); (renderer as Gtk.CellRendererToggle).Toggled += OnTaskToggled; column.PackStart (renderer, false); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (TaskToggleCellDataFunc)); AppendColumn (column); // // Priority Column // column = new Gtk.TreeViewColumn (); // Title for Priority Column column.Title = Catalog.GetString ("Priority"); //column.Sizing = Gtk.TreeViewColumnSizing.Autosize; column.Sizing = Gtk.TreeViewColumnSizing.Fixed; column.Alignment = 0.5f; column.FixedWidth = 30; column.Resizable = false; column.Clickable = true; renderer = new Gtk.CellRendererCombo (); (renderer as Gtk.CellRendererCombo).Editable = true; (renderer as Gtk.CellRendererCombo).HasEntry = false; SetCellRendererCallbacks ((CellRendererCombo) renderer, OnTaskPriorityEdited); Gtk.ListStore priorityStore = new Gtk.ListStore (typeof (string)); priorityStore.AppendValues (Catalog.GetString ("1")); // High priorityStore.AppendValues (Catalog.GetString ("2")); // Medium priorityStore.AppendValues (Catalog.GetString ("3")); // Low priorityStore.AppendValues (Catalog.GetString ("-")); // None (renderer as Gtk.CellRendererCombo).Model = priorityStore; (renderer as Gtk.CellRendererCombo).TextColumn = 0; renderer.Xalign = 0.5f; column.PackStart (renderer, true); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (TaskPriorityCellDataFunc)); AppendColumn (column); // // Task Name Column // column = new Gtk.TreeViewColumn (); // Title for Task Name Column column.Title = Catalog.GetString ("Task Name"); // column.Sizing = Gtk.TreeViewColumnSizing.Fixed; column.Sizing = Gtk.TreeViewColumnSizing.Autosize; column.Expand = true; column.Resizable = true; // TODO: Add in code to determine how wide we should make the name // column. // TODO: Add in code to readjust the size of the name column if the // user resizes the Task Window. //column.FixedWidth = 250; renderer = new Gtk.CellRendererText (); column.PackStart (renderer, true); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (TaskNameTextCellDataFunc)); ((Gtk.CellRendererText)renderer).Editable = true; SetCellRendererCallbacks ((CellRendererText) renderer, OnTaskNameEdited); AppendColumn (column); // // Due Date Column // // 2/11 - Today // 2/12 - Tomorrow // 2/13 - Wed // 2/14 - Thu // 2/15 - Fri // 2/16 - Sat // 2/17 - Sun // -------------- // 2/18 - In 1 Week // -------------- // No Date // --------------- // Choose Date... column = new Gtk.TreeViewColumn (); // Title for Due Date Column column.Title = Catalog.GetString ("Due Date"); column.Sizing = Gtk.TreeViewColumnSizing.Fixed; column.Alignment = 0f; column.FixedWidth = 90; column.Resizable = false; column.Clickable = true; renderer = new Gtk.CellRendererCombo (); (renderer as Gtk.CellRendererCombo).Editable = true; (renderer as Gtk.CellRendererCombo).HasEntry = false; SetCellRendererCallbacks ((CellRendererCombo) renderer, OnDateEdited); Gtk.ListStore dueDateStore = new Gtk.ListStore (typeof (string)); DateTime today = DateTime.Now; dueDateStore.AppendValues ( today.ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("Today")); dueDateStore.AppendValues ( today.AddDays(1).ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("Tomorrow")); dueDateStore.AppendValues ( today.AddDays(2).ToString(Catalog.GetString("M/d - ddd"))); dueDateStore.AppendValues ( today.AddDays(3).ToString(Catalog.GetString("M/d - ddd"))); dueDateStore.AppendValues ( today.AddDays(4).ToString(Catalog.GetString("M/d - ddd"))); dueDateStore.AppendValues ( today.AddDays(5).ToString(Catalog.GetString("M/d - ddd"))); dueDateStore.AppendValues ( today.AddDays(6).ToString(Catalog.GetString("M/d - ddd"))); dueDateStore.AppendValues ( today.AddDays(7).ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("In 1 Week")); dueDateStore.AppendValues (Catalog.GetString ("No Date")); dueDateStore.AppendValues (Catalog.GetString ("Choose Date...")); (renderer as Gtk.CellRendererCombo).Model = dueDateStore; (renderer as Gtk.CellRendererCombo).TextColumn = 0; renderer.Xalign = 0.0f; column.PackStart (renderer, true); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (DueDateCellDataFunc)); AppendColumn (column); // // Notes Column // column = new Gtk.TreeViewColumn (); // Title for Notes Column column.Title = Catalog.GetString ("Notes"); column.Sizing = Gtk.TreeViewColumnSizing.Fixed; column.FixedWidth = 20; column.Resizable = false; renderer = new Gtk.CellRendererPixbuf (); column.PackStart (renderer, false); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (TaskNotesCellDataFunc)); AppendColumn (column); // // Timer Column // column = new Gtk.TreeViewColumn (); // Title for Timer Column column.Title = Catalog.GetString ("Timer"); column.Sizing = Gtk.TreeViewColumnSizing.Fixed; column.FixedWidth = 20; column.Resizable = false; renderer = new Gtk.CellRendererPixbuf (); renderer.Xalign = 0.5f; column.PackStart (renderer, false); column.SetCellDataFunc (renderer, new Gtk.TreeCellDataFunc (TaskTimerCellDataFunc)); AppendColumn (column); } void CellRenderer_EditingStarted (object o, EditingStartedArgs args) { if (!toggled) return; Gtk.TreeIter iter; Gtk.TreePath path = new Gtk.TreePath (args.Path); if (!Model.GetIter (out iter, path)) return; ITask task = Model.GetValue (iter, 0) as ITask; if (task == null) return; taskBeingEdited = task; InactivateTimer.ToggleTimer (taskBeingEdited); } void SetCellRendererCallbacks (CellRendererText renderer, EditedHandler handler) { // The user is going to "edit" or "cancel", timer can't continue. renderer.EditingStarted += CellRenderer_EditingStarted; // Canceled: timer can continue. renderer.EditingCanceled += (o, args) => { if (toggled && taskBeingEdited != null) { taskBeingEdited.Inactivate (); InactivateTimer.ToggleTimer (taskBeingEdited); taskBeingEdited = null; toggled = false; } }; // Edited: after calling the delegate the timer can continue. renderer.Edited += (o, args) => { if (handler != null) handler (o, args); if (toggled && taskBeingEdited != null) { taskBeingEdited.Inactivate (); InactivateTimer.ToggleTimer (taskBeingEdited); taskBeingEdited = null; toggled = false; } }; } #region Public Methods public void Refilter () { Refilter (filterCategory); } public void Refilter (ICategory selectedCategory) { this.filterCategory = selectedCategory; Model = modelFilter; modelFilter.Refilter (); } public int GetNumberOfTasks () { return modelFilter.IterNChildren (); } #endregion // Public Methods #region Private Methods protected override void OnRealized () { base.OnRealized (); // Not sure why we need this, but without it, completed items are // initially appearing in the view. Refilter (filterCategory); } private static void ShowCompletedTaskStatus () { status = Catalog.GetString ("Task Completed"); TaskWindow.ShowStatus (status); } private void TaskToggleCellDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererToggle crt = cell as Gtk.CellRendererToggle; ITask task = model.GetValue (iter, 0) as ITask; if (task == null) crt.Active = false; else { crt.Active = task.State == TaskState.Active ? false : true; } } #if GTK_2_12 private void ConnectEvents() { this.CursorChanged += delegate(object o, EventArgs args) { int toolTipMaxLength = 250; string snipText = "..."; int maxNumNotes = 3; int notesAdded = 0; TooltipText = null; TriggerTooltipQuery(); TreeModel m; TreeIter iter; List<String> list = new List<String>(); if(Selection.GetSelected(out m, out iter)) { ITask task = Model.GetValue (iter, 0) as ITask; if (task != null && task.HasNotes && task.Notes != null) { foreach (INote note in task.Notes) { // for the tooltip, truncate any notes longer than 250 characters. if (note.Text.Length > toolTipMaxLength) list.Add(note.Text.Substring(0, toolTipMaxLength - snipText.Length) + snipText); else list.Add(note.Text); notesAdded++; // stop iterating once we reach maxNumNotes if (notesAdded >= maxNumNotes) { break; } } } HasTooltip = list.Count > 0; if (HasTooltip) { // if there are more than maxNumNotes, append a notice to the tooltip if (notesAdded < task.Notes.Count) { int nMoreNotes = task.Notes.Count - notesAdded; if (nMoreNotes > 1) list.Add(String.Format("[{0} more notes]", nMoreNotes)); else list.Add("[1 more note]"); } TooltipText = String.Join("\n\n", list.ToArray()); TriggerTooltipQuery(); } } }; } #endif void TaskPriorityCellDataFunc (Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel tree_model, Gtk.TreeIter iter) { // TODO: Add bold (for high), light (for None), and also colors to priority? Gtk.CellRendererCombo crc = cell as Gtk.CellRendererCombo; ITask task = Model.GetValue (iter, 0) as ITask; if (task == null) return; switch (task.Priority) { case TaskPriority.Low: crc.Text = Catalog.GetString ("3"); break; case TaskPriority.Medium: crc.Text = Catalog.GetString ("2"); break; case TaskPriority.High: crc.Text = Catalog.GetString ("1"); break; default: crc.Text = Catalog.GetString ("-"); break; } } private void TaskNameTextCellDataFunc (Gtk.TreeViewColumn treeColumn, Gtk.CellRenderer renderer, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText crt = renderer as Gtk.CellRendererText; crt.Ellipsize = Pango.EllipsizeMode.End; ITask task = model.GetValue (iter, 0) as ITask; if (task == null) { crt.Text = string.Empty; return; } string formatString = "{0}"; Preferences prefs = Application.Preferences; string todayTasksColor = prefs.Get (Preferences.TodayTaskTextColor); string overdueTaskColor = prefs.Get (Preferences.OverdueTaskTextColor); if (task.IsComplete) ; // Completed tasks colored below else if (task.DueDate.Date == DateTime.Today.Date) crt.Foreground = todayTasksColor; // Overdue and the task has a date assigned to it. else if (task.DueDate < DateTime.Today && task.DueDate != DateTime.MinValue) crt.Foreground = overdueTaskColor; switch (task.State) { case TaskState.Inactive: // Strikeout the text formatString = "<span strikethrough=\"true\">{0}</span>"; break; case TaskState.Deleted: case TaskState.Completed: // Gray out the text and add strikeout // TODO: Determine the grayed-out text color appropriate for the current theme formatString = "<span strikethrough=\"true\">{0}</span>"; crt.Foreground = "#AAAAAA"; break; } crt.Markup = string.Format (formatString, GLib.Markup.EscapeText (task.Name)); } protected virtual void DueDateCellDataFunc (Gtk.TreeViewColumn treeColumn, Gtk.CellRenderer renderer, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererCombo crc = renderer as Gtk.CellRendererCombo; ITask task = Model.GetValue (iter, 0) as ITask; if (task == null) return; DateTime date = task.State == TaskState.Completed ? task.CompletionDate : task.DueDate; if (date == DateTime.MinValue || date == DateTime.MaxValue) { crc.Text = "-"; return; } if (date.Year == DateTime.Today.Year) crc.Text = date.ToString(Catalog.GetString("M/d - ddd")); else crc.Text = date.ToString(Catalog.GetString("M/d/yy - ddd")); //Utilities.GetPrettyPrintDate (task.DueDate, false); } private void TaskNotesCellDataFunc (Gtk.TreeViewColumn treeColumn, Gtk.CellRenderer renderer, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererPixbuf crp = renderer as Gtk.CellRendererPixbuf; ITask task = model.GetValue (iter, 0) as ITask; if (task == null) { crp.Pixbuf = null; return; } crp.Pixbuf = task.HasNotes ? notePixbuf : null; } private void TaskTimerCellDataFunc (Gtk.TreeViewColumn treeColumn, Gtk.CellRenderer renderer, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererPixbuf crp = renderer as Gtk.CellRendererPixbuf; ITask task = model.GetValue (iter, 0) as ITask; if (task == null) return; if (task.State != TaskState.Inactive) { // The task is not in the inactive state so don't show any icon crp.Pixbuf = null; return; } Preferences prefs = Application.Preferences; int timerSeconds = prefs.GetInt (Preferences.InactivateTimeoutKey); // convert to milliseconds for more granularity long timeout = timerSeconds * 1000; //Logger.Debug ("TaskTimerCellDataFunc ()\n\tNow.Ticks: {0}\n\tCompletionDate.Ticks: {1}", // DateTime.Now.Ticks, task.CompletionDate.Ticks); long elapsedTicks = DateTime.Now.Ticks - task.CompletionDate.Ticks; //Logger.Debug ("\tElapsed Ticks: {0}", elapsedTicks); long elapsedMillis = elapsedTicks / 10000; //Logger.Debug ("\tElapsed Milliseconds: {0}", elapsedMillis); double percentComplete = (double)elapsedMillis / (double)timeout; //Logger.Debug ("\tPercent Complete: {0}", percentComplete); Gdk.Pixbuf pixbuf = GetIconForPercentage (percentComplete * 100); crp.Pixbuf = pixbuf; } protected static Gdk.Pixbuf GetIconForPercentage (double timeoutPercent) { int iconNum = GetIconNumForPercentage (timeoutPercent); if (iconNum == -1 || iconNum > 11) return null; return inactiveAnimPixbufs [iconNum]; } protected static int GetIconNumForPercentage (double timeoutPercent) { //Logger.Debug ("GetIconNumForPercentage: {0}", timeoutPercent); int numOfIcons = 12; double percentIncrement = (double)100 / (double)numOfIcons; //Logger.Debug ("\tpercentIncrement: {0}", percentIncrement); if (timeoutPercent < percentIncrement) return 0; if (timeoutPercent < percentIncrement * 2) return 1; if (timeoutPercent < percentIncrement * 3) return 2; if (timeoutPercent < percentIncrement * 4) return 3; if (timeoutPercent < percentIncrement * 5) return 4; if (timeoutPercent < percentIncrement * 6) return 5; if (timeoutPercent < percentIncrement * 7) return 6; if (timeoutPercent < percentIncrement * 8) return 7; if (timeoutPercent < percentIncrement * 9) return 8; if (timeoutPercent < percentIncrement * 10) return 9; if (timeoutPercent < percentIncrement * 11) return 10; if (timeoutPercent < percentIncrement * 12) return 11; return -1; } protected virtual bool FilterFunc (Gtk.TreeModel model, Gtk.TreeIter iter) { // Filter out deleted tasks ITask task = model.GetValue (iter, 0) as ITask; if (task == null) { Logger.Error ("FilterFunc: task at iter was null"); return false; } if (task.State == TaskState.Deleted) { //Logger.Debug ("TaskTreeView.FilterFunc:\n\t{0}\n\t{1}\n\tReturning false", task.Name, task.State); return false; } if (filterCategory == null) return true; return filterCategory.ContainsTask (task); } #endregion // Private Methods #region EventHandlers void OnTaskToggled (object sender, Gtk.ToggledArgs args) { Logger.Debug ("OnTaskToggled"); Gtk.TreeIter iter; Gtk.TreePath path = new Gtk.TreePath (args.Path); if (!Model.GetIter (out iter, path)) return; // Do nothing ITask task = Model.GetValue (iter, 0) as ITask; if (task == null) return; // remove any timer set up on this task InactivateTimer.CancelTimer(task); if (task.State == TaskState.Active) { bool showCompletedTasks = Application.Preferences.GetBool ( Preferences.ShowCompletedTasksKey); // When showCompletedTasks is true, complete the tasks right // away. Otherwise, set a timer and show the timer animation // before marking the task completed. if (showCompletedTasks) { task.Complete (); ShowCompletedTaskStatus (); } else { task.Inactivate (); // Read the inactivate timeout from a preference int timeout = Application.Preferences.GetInt (Preferences.InactivateTimeoutKey); Logger.Debug ("Read timeout from prefs: {0}", timeout); InactivateTimer timer = new InactivateTimer (this, iter, task, (uint) timeout); timer.StartTimer (); toggled = true; } } else { status = Catalog.GetString ("Action Canceled"); TaskWindow.ShowStatus (status); task.Activate (); } } void OnTaskPriorityEdited (object sender, Gtk.EditedArgs args) { Gtk.TreeIter iter; Gtk.TreePath path = new TreePath (args.Path); if (!Model.GetIter (out iter, path)) return; TaskPriority newPriority; if (args.NewText.CompareTo (Catalog.GetString ("3")) == 0) newPriority = TaskPriority.Low; else if (args.NewText.CompareTo (Catalog.GetString ("2")) == 0) newPriority = TaskPriority.Medium; else if (args.NewText.CompareTo (Catalog.GetString ("1")) == 0) newPriority = TaskPriority.High; else newPriority = TaskPriority.None; // Update the priority if it's different ITask task = Model.GetValue (iter, 0) as ITask; if (task.Priority != newPriority) task.Priority = newPriority; } void OnTaskNameEdited (object sender, Gtk.EditedArgs args) { Gtk.TreeIter iter; Gtk.TreePath path = new TreePath (args.Path); if (!Model.GetIter (out iter, path)) return; ITask task = Model.GetValue (iter, 0) as ITask; if (task == null) return; string newText = args.NewText; // Attempt to derive due date information from text. if (Application.Preferences.GetBool (Preferences.ParseDateEnabledKey) && task.State == TaskState.Active && task.DueDate == DateTime.MinValue) { string parsedTaskText; DateTime parsedDueDate; TaskParser.Instance.TryParse (newText, out parsedTaskText, out parsedDueDate); if (parsedDueDate != DateTime.MinValue) task.DueDate = parsedDueDate; newText = parsedTaskText; } task.Name = newText; } /// <summary> /// Modify the due date or completion date depending on whether the /// task being modified is completed or active. /// </summary> /// <param name="sender"> /// A <see cref="System.Object"/> /// </param> /// <param name="args"> /// A <see cref="Gtk.EditedArgs"/> /// </param> void OnDateEdited (object sender, Gtk.EditedArgs args) { if (args.NewText == null) { Logger.Debug ("New date text null, not setting date"); return; } Gtk.TreeIter iter; Gtk.TreePath path = new TreePath (args.Path); if (!Model.GetIter (out iter, path)) return; // 2/11 - Today // 2/12 - Tomorrow // 2/13 - Wed // 2/14 - Thu // 2/15 - Fri // 2/16 - Sat // 2/17 - Sun // -------------- // 2/18 - In 1 Week // -------------- // No Date // --------------- // Choose Date... DateTime newDate = DateTime.MinValue; DateTime today = DateTime.Now; ITask task = Model.GetValue (iter, 0) as ITask; if (args.NewText.CompareTo ( today.ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("Today") ) == 0) newDate = today; else if (args.NewText.CompareTo ( today.AddDays(1).ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("Tomorrow") ) == 0) newDate = today.AddDays (1); else if (args.NewText.CompareTo (Catalog.GetString ("No Date")) == 0) newDate = DateTime.MinValue; else if (args.NewText.CompareTo ( today.AddDays(7).ToString(Catalog.GetString("M/d - ")) + Catalog.GetString("In 1 Week") ) == 0) newDate = today.AddDays (7); else if (args.NewText.CompareTo (Catalog.GetString ("Choose Date...")) == 0) { TaskCalendar tc = new TaskCalendar(task, this.Parent); tc.ShowCalendar(); return; } else { for (int i = 2; i <= 6; i++) { DateTime testDate = today.AddDays (i); if (testDate.ToString(Catalog.GetString("M/d - ddd")).CompareTo ( args.NewText) == 0) { newDate = testDate; break; } } } Console.WriteLine ("task.State {0}", task.State); if (task.State == TaskState.Completed) { // Modify the completion date task.CompletionDate = newDate; } else { // Modify the due date task.DueDate = newDate; } } void OnRowInsertedHandler (object sender, Gtk.RowInsertedArgs args) { if (NumberOfTasksChanged == null) return; NumberOfTasksChanged (this, EventArgs.Empty); } void OnRowDeletedHandler (object sender, Gtk.RowDeletedArgs args) { if (NumberOfTasksChanged == null) return; NumberOfTasksChanged (this, EventArgs.Empty); } #endregion // EventHandlers #region Private Classes /// <summary> /// Does the work of walking a task through the Inactive -> Complete /// states /// </summary> class InactivateTimer { /// <summary> /// Keep track of all the timers so that the pulseTimeoutId can /// be removed at the proper time. /// </summary> private static Dictionary<uint, InactivateTimer> timers; static InactivateTimer () { timers = new Dictionary<uint,InactivateTimer> (); } private TaskTreeView tree; private ITask task; private uint delay; private uint secondsLeft; protected uint pulseTimeoutId; private uint secondTimerId; private Gtk.TreeIter iter; private Gtk.TreePath path; public InactivateTimer (TaskTreeView treeView, Gtk.TreeIter taskIter, ITask taskToComplete, uint delayInSeconds) { tree = treeView; iter = taskIter; path = treeView.Model.GetPath (iter); task = taskToComplete; secondsLeft = delayInSeconds; delay = delayInSeconds * 1000; // Convert to milliseconds pulseTimeoutId = 0; } public bool Paused { get; set; } public void StartTimer () { pulseTimeoutId = GLib.Timeout.Add (500, PulseAnimation); StartSecondCountdown (); task.TimerID = GLib.Timeout.Add (delay, CompleteTask); timers [task.TimerID] = this; } public static void ToggleTimer (ITask task) { InactivateTimer timer = null; if (timers.TryGetValue (task.TimerID, out timer)) timer.Paused = !timer.Paused; } public static void CancelTimer(ITask task) { Logger.Debug ("Timeout Canceled for task: " + task.Name); InactivateTimer timer = null; uint timerId = task.TimerID; if(timerId != 0) { if (timers.ContainsKey (timerId)) { timer = timers [timerId]; timers.Remove (timerId); } GLib.Source.Remove(timerId); GLib.Source.Remove (timer.pulseTimeoutId); timer.pulseTimeoutId = 0; task.TimerID = 0; } if (timer != null) { GLib.Source.Remove (timer.pulseTimeoutId); timer.pulseTimeoutId = 0; GLib.Source.Remove (timer.secondTimerId); timer.secondTimerId = 0; timer.Paused = false; } } private bool CompleteTask () { if (!Paused) { GLib.Source.Remove (pulseTimeoutId); if (timers.ContainsKey (task.TimerID)) timers.Remove (task.TimerID); if(task.State != TaskState.Inactive) return false; task.Complete (); ShowCompletedTaskStatus (); tree.Refilter (); return false; // Don't automatically call this handler again } return true; } private bool PulseAnimation () { if (tree.Model == null) { // Widget has been closed, no need to call this again return false; } else { if (!Paused) { // Emit this signal to cause the TreeView to update the row // where the task is located. This will allow the // CellRendererPixbuf to update the icon. tree.Model.EmitRowChanged (path, iter); // Return true so that this method will be called after an // additional timeout duration has elapsed. return true; } } return true; } private void StartSecondCountdown () { SecondCountdown(); secondTimerId = GLib.Timeout.Add (1000, SecondCountdown); } private bool SecondCountdown () { if (tree.Model == null) { // Widget has been closed, no need to call this again return false; } if (!Paused) { if (secondsLeft > 0 && task.State == TaskState.Inactive) { status = String.Format (Catalog.GetString ("Completing Task In: {0}"), secondsLeft--); TaskWindow.ShowStatus (status); return true; } else { return false; } } return true; } } #endregion // Private Classes } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; /// @file /// @addtogroup flatbuffers_csharp_api /// @{ namespace FlatBuffers { /// <summary> /// Responsible for building up and accessing a FlatBuffer formatted byte /// array (via ByteBuffer). /// </summary> public class FlatBufferBuilder { private int _space; private ByteBuffer _bb; private int _minAlign = 1; // The vtable for the current table (if _vtableSize >= 0) private int[] _vtable = new int[16]; // The size of the vtable. -1 indicates no vtable private int _vtableSize = -1; // Starting offset of the current struct/table. private int _objectStart; // List of offsets of all vtables. private int[] _vtables = new int[16]; // Number of entries in `vtables` in use. private int _numVtables = 0; // For the current vector being built. private int _vectorNumElems = 0; /// <summary> /// Create a FlatBufferBuilder with a given initial size. /// </summary> /// <param name="initialSize"> /// The initial size to use for the internal buffer. /// </param> public FlatBufferBuilder(int initialSize) { if (initialSize <= 0) throw new ArgumentOutOfRangeException("initialSize", initialSize, "Must be greater than zero"); _space = initialSize; _bb = new ByteBuffer(initialSize); } /// <summary> /// Create a FlatBufferBuilder backed by the pased in ByteBuffer /// </summary> /// <param name="buffer">The ByteBuffer to write to</param> public FlatBufferBuilder(ByteBuffer buffer) { _bb = buffer; _space = buffer.Length; buffer.Reset(); } /// <summary> /// Reset the FlatBufferBuilder by purging all data that it holds. /// </summary> public void Clear() { _space = _bb.Length; _bb.Reset(); _minAlign = 1; while (_vtableSize > 0) _vtable[--_vtableSize] = 0; _vtableSize = -1; _objectStart = 0; _numVtables = 0; _vectorNumElems = 0; } /// <summary> /// Gets and sets a Boolean to disable the optimization when serializing /// default values to a Table. /// /// In order to save space, fields that are set to their default value /// don't get serialized into the buffer. /// </summary> public bool ForceDefaults { get; set; } /// @cond FLATBUFFERS_INTERNAL public int Offset { get { return _bb.Length - _space; } } public void Pad(int size) { _bb.PutByte(_space -= size, 0, size); } // Doubles the size of the ByteBuffer, and copies the old data towards // the end of the new buffer (since we build the buffer backwards). void GrowBuffer() { _bb.GrowFront(_bb.Length << 1); } // Prepare to write an element of `size` after `additional_bytes` // have been written, e.g. if you write a string, you need to align // such the int length field is aligned to SIZEOF_INT, and the string // data follows it directly. // If all you need to do is align, `additional_bytes` will be 0. public void Prep(int size, int additionalBytes) { // Track the biggest thing we've ever aligned to. if (size > _minAlign) _minAlign = size; // Find the amount of alignment needed such that `size` is properly // aligned after `additional_bytes` var alignSize = ((~((int)_bb.Length - _space + additionalBytes)) + 1) & (size - 1); // Reallocate the buffer if needed. while (_space < alignSize + size + additionalBytes) { var oldBufSize = (int)_bb.Length; GrowBuffer(); _space += (int)_bb.Length - oldBufSize; } if (alignSize > 0) Pad(alignSize); } public void PutBool(bool x) { _bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0)); } public void PutSbyte(sbyte x) { _bb.PutSbyte(_space -= sizeof(sbyte), x); } public void PutByte(byte x) { _bb.PutByte(_space -= sizeof(byte), x); } public void PutShort(short x) { _bb.PutShort(_space -= sizeof(short), x); } public void PutUshort(ushort x) { _bb.PutUshort(_space -= sizeof(ushort), x); } public void PutInt(int x) { _bb.PutInt(_space -= sizeof(int), x); } public void PutUint(uint x) { _bb.PutUint(_space -= sizeof(uint), x); } public void PutLong(long x) { _bb.PutLong(_space -= sizeof(long), x); } public void PutUlong(ulong x) { _bb.PutUlong(_space -= sizeof(ulong), x); } public void PutFloat(float x) { _bb.PutFloat(_space -= sizeof(float), x); } /// <summary> /// Puts an array of type T into this builder at the /// current offset /// </summary> /// <typeparam name="T">The type of the input data </typeparam> /// <param name="x">The array to copy data from</param> public void Put<T>(T[] x) where T : struct { _space = _bb.Put(_space, x); } #if ENABLE_SPAN_T /// <summary> /// Puts a span of type T into this builder at the /// current offset /// </summary> /// <typeparam name="T">The type of the input data </typeparam> /// <param name="x">The span to copy data from</param> public void Put<T>(Span<T> x) where T : struct { _space = _bb.Put(_space, x); } #endif public void PutDouble(double x) { _bb.PutDouble(_space -= sizeof(double), x); } /// @endcond /// <summary> /// Add a `bool` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `bool` to add to the buffer.</param> public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); } /// <summary> /// Add a `sbyte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `sbyte` to add to the buffer.</param> public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); } /// <summary> /// Add a `byte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `byte` to add to the buffer.</param> public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); } /// <summary> /// Add a `short` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `short` to add to the buffer.</param> public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); } /// <summary> /// Add an `ushort` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ushort` to add to the buffer.</param> public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); } /// <summary> /// Add an `int` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `int` to add to the buffer.</param> public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); } /// <summary> /// Add an `uint` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `uint` to add to the buffer.</param> public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); } /// <summary> /// Add a `long` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `long` to add to the buffer.</param> public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); } /// <summary> /// Add an `ulong` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ulong` to add to the buffer.</param> public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); } /// <summary> /// Add a `float` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `float` to add to the buffer.</param> public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); } /// <summary> /// Add an array of type T to the buffer (aligns the data and grows if necessary). /// </summary> /// <typeparam name="T">The type of the input data</typeparam> /// <param name="x">The array to copy data from</param> public void Add<T>(T[] x) where T : struct { if (x == null) { throw new ArgumentNullException("Cannot add a null array"); } if( x.Length == 0) { // don't do anything if the array is empty return; } if(!ByteBuffer.IsSupportedType<T>()) { throw new ArgumentException("Cannot add this Type array to the builder"); } int size = ByteBuffer.SizeOf<T>(); // Need to prep on size (for data alignment) and then we pass the // rest of the length (minus 1) as additional bytes Prep(size, size * (x.Length - 1)); Put(x); } #if ENABLE_SPAN_T /// <summary> /// Add a span of type T to the buffer (aligns the data and grows if necessary). /// </summary> /// <typeparam name="T">The type of the input data</typeparam> /// <param name="x">The span to copy data from</param> public void Add<T>(Span<T> x) where T : struct { if (!ByteBuffer.IsSupportedType<T>()) { throw new ArgumentException("Cannot add this Type array to the builder"); } int size = ByteBuffer.SizeOf<T>(); // Need to prep on size (for data alignment) and then we pass the // rest of the length (minus 1) as additional bytes Prep(size, size * (x.Length - 1)); Put(x); } #endif /// <summary> /// Add a `double` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `double` to add to the buffer.</param> public void AddDouble(double x) { Prep(sizeof(double), 0); PutDouble(x); } /// <summary> /// Adds an offset, relative to where it will be written. /// </summary> /// <param name="off">The offset to add to the buffer.</param> public void AddOffset(int off) { Prep(sizeof(int), 0); // Ensure alignment is already done. if (off > Offset) throw new ArgumentException(); off = Offset - off + sizeof(int); PutInt(off); } /// @cond FLATBUFFERS_INTERNAL public void StartVector(int elemSize, int count, int alignment) { NotNested(); _vectorNumElems = count; Prep(sizeof(int), elemSize * count); Prep(alignment, elemSize * count); // Just in case alignment > int. } /// @endcond /// <summary> /// Writes data necessary to finish a vector construction. /// </summary> public VectorOffset EndVector() { PutInt(_vectorNumElems); return new VectorOffset(Offset); } /// <summary> /// Creates a vector of tables. /// </summary> /// <param name="offsets">Offsets of the tables.</param> public VectorOffset CreateVectorOfTables<T>(Offset<T>[] offsets) where T : struct { NotNested(); StartVector(sizeof(int), offsets.Length, sizeof(int)); for (int i = offsets.Length - 1; i >= 0; i--) AddOffset(offsets[i].Value); return EndVector(); } /// @cond FLATBUFFERS_INTENRAL public void Nested(int obj) { // Structs are always stored inline, so need to be created right // where they are used. You'll get this assert if you created it // elsewhere. if (obj != Offset) throw new Exception( "FlatBuffers: struct must be serialized inline."); } public void NotNested() { // You should not be creating any other objects or strings/vectors // while an object is being constructed if (_vtableSize >= 0) throw new Exception( "FlatBuffers: object serialization must not be nested."); } public void StartObject(int numfields) { if (numfields < 0) throw new ArgumentOutOfRangeException("Flatbuffers: invalid numfields"); NotNested(); if (_vtable.Length < numfields) _vtable = new int[numfields]; _vtableSize = numfields; _objectStart = Offset; } // Set the current vtable at `voffset` to the current location in the // buffer. public void Slot(int voffset) { if (voffset >= _vtableSize) throw new IndexOutOfRangeException("Flatbuffers: invalid voffset"); _vtable[voffset] = Offset; } /// <summary> /// Adds a Boolean to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddBool(int o, bool x, bool d) { if (ForceDefaults || x != d) { AddBool(x); Slot(o); } } /// <summary> /// Adds a SByte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddSbyte(int o, sbyte x, sbyte d) { if (ForceDefaults || x != d) { AddSbyte(x); Slot(o); } } /// <summary> /// Adds a Byte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddByte(int o, byte x, byte d) { if (ForceDefaults || x != d) { AddByte(x); Slot(o); } } /// <summary> /// Adds a Int16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddShort(int o, short x, int d) { if (ForceDefaults || x != d) { AddShort(x); Slot(o); } } /// <summary> /// Adds a UInt16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUshort(int o, ushort x, ushort d) { if (ForceDefaults || x != d) { AddUshort(x); Slot(o); } } /// <summary> /// Adds an Int32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddInt(int o, int x, int d) { if (ForceDefaults || x != d) { AddInt(x); Slot(o); } } /// <summary> /// Adds a UInt32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUint(int o, uint x, uint d) { if (ForceDefaults || x != d) { AddUint(x); Slot(o); } } /// <summary> /// Adds an Int64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddLong(int o, long x, long d) { if (ForceDefaults || x != d) { AddLong(x); Slot(o); } } /// <summary> /// Adds a UInt64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUlong(int o, ulong x, ulong d) { if (ForceDefaults || x != d) { AddUlong(x); Slot(o); } } /// <summary> /// Adds a Single to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddFloat(int o, float x, double d) { if (ForceDefaults || x != d) { AddFloat(x); Slot(o); } } /// <summary> /// Adds a Double to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddDouble(int o, double x, double d) { if (ForceDefaults || x != d) { AddDouble(x); Slot(o); } } /// <summary> /// Adds a buffer offset to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddOffset(int o, int x, int d) { if (ForceDefaults || x != d) { AddOffset(x); Slot(o); } } /// @endcond /// <summary> /// Encode the string `s` in the buffer using UTF-8. /// </summary> /// <param name="s">The string to encode.</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateString(string s) { NotNested(); AddByte(0); var utf8StringLen = Encoding.UTF8.GetByteCount(s); StartVector(1, utf8StringLen, 1); _bb.PutStringUTF8(_space -= utf8StringLen, s); return new StringOffset(EndVector().Value); } #if ENABLE_SPAN_T /// <summary> /// Creates a string in the buffer from a Span containing /// a UTF8 string. /// </summary> /// <param name="chars">the UTF8 string to add to the buffer</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateUTF8String(Span<byte> chars) { NotNested(); AddByte(0); var utf8StringLen = chars.Length; StartVector(1, utf8StringLen, 1); _space = _bb.Put(_space, chars); return new StringOffset(EndVector().Value); } #endif /// @cond FLATBUFFERS_INTERNAL // Structs are stored inline, so nothing additional is being added. // `d` is always 0. public void AddStruct(int voffset, int x, int d) { if (x != d) { Nested(x); Slot(voffset); } } public int EndObject() { if (_vtableSize < 0) throw new InvalidOperationException( "Flatbuffers: calling endObject without a startObject"); AddInt((int)0); var vtableloc = Offset; // Write out the current vtable. int i = _vtableSize - 1; // Trim trailing zeroes. for (; i >= 0 && _vtable[i] == 0; i--) {} int trimmedSize = i + 1; for (; i >= 0 ; i--) { // Offset relative to the start of the table. short off = (short)(_vtable[i] != 0 ? vtableloc - _vtable[i] : 0); AddShort(off); // clear out written entry _vtable[i] = 0; } const int standardFields = 2; // The fields below: AddShort((short)(vtableloc - _objectStart)); AddShort((short)((trimmedSize + standardFields) * sizeof(short))); // Search for an existing vtable that matches the current one. int existingVtable = 0; for (i = 0; i < _numVtables; i++) { int vt1 = _bb.Length - _vtables[i]; int vt2 = _space; short len = _bb.GetShort(vt1); if (len == _bb.GetShort(vt2)) { for (int j = sizeof(short); j < len; j += sizeof(short)) { if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) { goto endLoop; } } existingVtable = _vtables[i]; break; } endLoop: { } } if (existingVtable != 0) { // Found a match: // Remove the current vtable. _space = _bb.Length - vtableloc; // Point table to existing vtable. _bb.PutInt(_space, existingVtable - vtableloc); } else { // No match: // Add the location of the current vtable to the list of // vtables. if (_numVtables == _vtables.Length) { // Arrays.CopyOf(vtables num_vtables * 2); var newvtables = new int[ _numVtables * 2]; Array.Copy(_vtables, newvtables, _vtables.Length); _vtables = newvtables; }; _vtables[_numVtables++] = Offset; // Point table to current vtable. _bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); } _vtableSize = -1; return vtableloc; } // This checks a required field has been set in a given table that has // just been constructed. public void Required(int table, int field) { int table_start = _bb.Length - table; int vtable_start = table_start - _bb.GetInt(table_start); bool ok = _bb.GetShort(vtable_start + field) != 0; // If this fails, the caller will show what field needs to be set. if (!ok) throw new InvalidOperationException("FlatBuffers: field " + field + " must be set"); } /// @endcond /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0)); AddOffset(rootTable); if (sizePrefix) { AddInt(_bb.Length - _space); } _bb.Position = _space; } /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void Finish(int rootTable) { Finish(rootTable, false); } /// <summary> /// Finalize a buffer, pointing to the given `root_table`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void FinishSizePrefixed(int rootTable) { Finish(rootTable, true); } /// <summary> /// Get the ByteBuffer representing the FlatBuffer. /// </summary> /// <remarks> /// This is typically only called after you call `Finish()`. /// The actual data starts at the ByteBuffer's current position, /// not necessarily at `0`. /// </remarks> /// <returns> /// Returns the ByteBuffer for this FlatBuffer. /// </returns> public ByteBuffer DataBuffer { get { return _bb; } } /// <summary> /// A utility function to copy and return the ByteBuffer data as a /// `byte[]`. /// </summary> /// <returns> /// A full copy of the FlatBuffer data. /// </returns> public byte[] SizedByteArray() { return _bb.ToSizedArray(); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, string fileIdentifier, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0) + FlatBufferConstants.FileIdentifierLength); if (fileIdentifier.Length != FlatBufferConstants.FileIdentifierLength) throw new ArgumentException( "FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "fileIdentifier"); for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0; i--) { AddByte((byte)fileIdentifier[i]); } Finish(rootTable, sizePrefix); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void Finish(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, false); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void FinishSizePrefixed(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, true); } } } /// @}
using System; using System.Threading; using NationalInstruments.DAQmx; using DAQ.Environment; namespace DAQ.HAL { /// <summary> /// A class to control the PatternList generator using DAQMx. This class is not horrible, doesn't /// suffer from huge memory leaks, and doesn't frequently crash the computer. W00t. /// </summary> public class DAQMxPatternGenerator : PatternGenerator { private Task pgTask; private String pgTaskName; private String device; private DigitalSingleChannelWriter writer; private double clockFrequency; private int length; // this task is used to generate the sample clock on the "integrated" 6229-type PGs private Task counterTask; string clock_line; private bool taskRunning; public DAQMxPatternGenerator(String device) { this.device = device; } // use this method to output a PatternList to the whole PatternList generator public void OutputPattern(UInt32[] pattern) { //writer.WriteMultiSamplePort(false, pattern); //taskRunning = true; //pgTask.Start(); //SleepOnePattern(); OutputPattern(pattern, true); } public void OutputPattern(UInt32[] pattern, bool sleep) { //writer.WriteMultiSamplePort(false, pattern); //taskRunning = true; //pgTask.Start(); writer.WriteMultiSamplePort(false, pattern); pgTask.Start(); if(sleep==true) SleepOnePattern(); } // use this method to output a PatternList to half of the PatternList generator public void OutputPattern(Int16[] pattern) { writer.WriteMultiSamplePort(true, pattern); SleepOnePattern(); } private void SleepOnePattern() { // This Sleep is important (or at least it may be). It's here to guarantee that the correct PatternList is // being output by the time this call returns. This is needed to make the tweak // and pg scans work correctly. It has the side effect that you have to wait for // at least one copy of the PatternList to output before you can do anything. This means // pg scans are slowed down by a factor of two. I can't think of a better way to do // it at the moment. // It might be possible to speed it up by understanding the timing of the above call // - when does it return ? int sleepTime = (int)(((double)length * 1000) / clockFrequency); Thread.Sleep(sleepTime); //Sleep until Task is finished at which point taskRunning becomes false. //while (taskRunning == true) ; } public void Configure(string taskName, double clockFrequency, bool loop, bool fullWidth, bool lowGroup, int length, bool internalClock, bool triggered) { pgTask = new Task(taskName); pgTaskName = taskName; clock_line = pgTaskName + "ClockLine"; configure_PG(clockFrequency, loop, fullWidth, lowGroup, length, internalClock, triggered); } public void Configure(double clockFrequency, bool loop, bool fullWidth, bool lowGroup, int length, bool internalClock, bool triggered) { //pgTask = new Task("pgTask"); pgTask = new Task("PG"); pgTaskName = "PG"; clock_line = pgTaskName + "ClockLine"; configure_PG(clockFrequency, loop, fullWidth, lowGroup, length, internalClock, triggered); } private void configure_PG(double clockFrequency, bool loop, bool fullWidth, bool lowGroup, int length, bool internalClock, bool triggered) { this.clockFrequency = clockFrequency; this.length = length; /**** Configure the output lines ****/ // The underscore notation is the way to address more than 8 of the PatternList generator // lines at once. This is really buried in the NI-DAQ documentation ! String chanString = ""; if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated") { if (fullWidth) chanString = device + "/port0_32"; else { if (lowGroup) chanString = device + "/port0_16"; else chanString = device + "/port3_16"; } } // as far as I know you can only address the whole 32-bit port on the 6229 type integrated PatternList generators if ((string)Environs.Hardware.GetInfo("PGType") == "integrated") { chanString = device + "/port0"; } DOChannel doChan = pgTask.DOChannels.CreateChannel( chanString, "pg", ChannelLineGrouping.OneChannelForAllLines ); /**** Configure the clock ****/ String clockSource = ""; if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated") { if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo(clock_line); else clockSource = ""; } if ((string)Environs.Hardware.GetInfo("PGType") == "integrated") { // clocking is more complicated for the 6229 style PG boards as they don't have their own internal clock. // if external clocking is required it's easy: if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo(clock_line); else { // if an internal clock is requested we generate it using the card's timer/counters. counterTask = new Task(); counterTask.COChannels.CreatePulseChannelFrequency( device + (string)Environs.Hardware.GetInfo("PGClockCounter"), "PG Clock", COPulseFrequencyUnits.Hertz, COPulseIdleState.Low, 0.0, clockFrequency, 0.5 ); counterTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples; //When just setting this attibute SQM seems to revert to finite samples when //task is started. So use the following method to configure SQM. counterTask.Timing.ConfigureImplicit(SampleQuantityMode.ContinuousSamples); counterTask.Start(); clockSource = device + (string)Environs.Hardware.GetInfo("PGClockCounter") + "InternalOutput"; } } /**** Configure regeneration ****/ SampleQuantityMode sqm; if (loop) { sqm = SampleQuantityMode.ContinuousSamples; pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration; } else { sqm = SampleQuantityMode.FiniteSamples; pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration; } pgTask.Timing.ConfigureSampleClock( clockSource, clockFrequency, SampleClockActiveEdge.Rising, sqm, length ); /* Configure one of the PFI channels to output the clock signal of the master card. Required to synchronize the slaves when using multiple pattern cards */ if (pgTaskName == "PG") pgTask.ExportSignals.SampleClockOutputTerminal = (string)Environment.Environs.Hardware.GetInfo(clock_line); /* if (device == "/Dev1") pgTask.ExportSignals.SampleClockOutputTerminal = device + "/PFI2"; */ /**** Configure buffering ****/ if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated") { // these lines are critical - without them DAQMx copies the data you provide // as many times as it can into the on board FIFO (the cited reason being stability). // This has the annoying side effect that you have to wait for the on board buffer // to stream out before you can update the patterns - this takes ~6 seconds at 1MHz. // These lines tell the board and the software to use buffers as close to the size of // the PatternList as possible (on board buffer size is coerced to be related to a power of // two, so you don't quite get what you ask for). // note that 6229 type integrated PGs only have 2kB buffer, so this isn't needed for them (or allowed, in fact) pgTask.Stream.Buffer.OutputBufferSize = length; pgTask.Stream.Buffer.OutputOnBoardBufferSize = length; } /**** Configure triggering ****/ if (triggered) { pgTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger( (string)Environs.Hardware.GetInfo(pgTaskName + "TriggerLine"), DigitalEdgeStartTriggerEdge.Rising); } /**** Write configuration to board ****/ pgTask.Control(TaskAction.Commit); writer = new DigitalSingleChannelWriter(pgTask.Stream); pgTask.Done += new TaskDoneEventHandler(pgTask_Done); } public void StopPattern() { if (pgTask != null) pgTask.Dispose(); if ((string)Environs.Hardware.GetInfo("PGType") == "integrated") counterTask.Dispose(); } private void pgTask_Done(object sender, TaskDoneEventArgs e) { taskRunning = false; if (pgTask != null) { pgTask.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using DDDSyd2016.Areas.HelpPage.ModelDescriptions; using DDDSyd2016.Areas.HelpPage.Models; namespace DDDSyd2016.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal partial class CMemberLookupResults { public partial class CMethodIterator { private SymbolLoader _pSymbolLoader; private CSemanticChecker _pSemanticChecker; // Inputs. private AggregateType _pCurrentType; private MethodOrPropertySymbol _pCurrentSym; private AggregateDeclaration _pContext; private TypeArray _pContainingTypes; private CType _pQualifyingType; private Name _pName; private int _nArity; private symbmask_t _mask; private EXPRFLAG _flags; // Internal state. private int _nCurrentTypeCount; private bool _bIsCheckingInstanceMethods; private bool _bAtEnd; private bool _bAllowBogusAndInaccessible; // Flags for the current sym. private bool _bCurrentSymIsBogus; private bool _bCurrentSymIsInaccessible; // if Extension can be part of the results that are returned by the iterator // this may be false if an applicable instance method was found by bindgrptoArgs private bool _bcanIncludeExtensionsInResults; public CMethodIterator(CSemanticChecker checker, SymbolLoader symLoader, Name name, TypeArray containingTypes, CType @object, CType qualifyingType, AggregateDeclaration context, bool allowBogusAndInaccessible, bool allowExtensionMethods, int arity, EXPRFLAG flags, symbmask_t mask) { Debug.Assert(name != null); Debug.Assert(symLoader != null); Debug.Assert(checker != null); Debug.Assert(containingTypes != null); _pSemanticChecker = checker; _pSymbolLoader = symLoader; _pCurrentType = null; _pCurrentSym = null; _pName = name; _pContainingTypes = containingTypes; _pQualifyingType = qualifyingType; _pContext = context; _bAllowBogusAndInaccessible = allowBogusAndInaccessible; _nArity = arity; _flags = flags; _mask = mask; _nCurrentTypeCount = 0; _bIsCheckingInstanceMethods = true; _bAtEnd = false; _bCurrentSymIsBogus = false; _bCurrentSymIsInaccessible = false; _bcanIncludeExtensionsInResults = allowExtensionMethods; } public MethodOrPropertySymbol GetCurrentSymbol() { return _pCurrentSym; } public AggregateType GetCurrentType() { return _pCurrentType; } public bool IsCurrentSymbolInaccessible() { return _bCurrentSymIsInaccessible; } public bool IsCurrentSymbolBogus() { return _bCurrentSymIsBogus; } public bool MoveNext(bool canIncludeExtensionsInResults) { if (_bcanIncludeExtensionsInResults) { _bcanIncludeExtensionsInResults = canIncludeExtensionsInResults; } if (_bAtEnd) { return false; } if (_pCurrentType == null) // First guy. { if (_pContainingTypes.Count == 0) { // No instance methods, only extensions. _bIsCheckingInstanceMethods = false; _bAtEnd = true; return false; } else { if (!FindNextTypeForInstanceMethods()) { // No instance or extensions. _bAtEnd = true; return false; } } } if (!FindNextMethod()) { _bAtEnd = true; return false; } return true; } public bool AtEnd() { return _pCurrentSym == null; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } public bool CanUseCurrentSymbol() { _bCurrentSymIsInaccessible = false; _bCurrentSymIsBogus = false; // Make sure that whether we're seeing a ctor is consistent with the flag. // The only properties we handle are indexers. if (_mask == symbmask_t.MASK_MethodSymbol && ( 0 == (_flags & EXPRFLAG.EXF_CTOR) != !((MethodSymbol)_pCurrentSym).IsConstructor() || 0 == (_flags & EXPRFLAG.EXF_OPERATOR) != !((MethodSymbol)_pCurrentSym).isOperator) || _mask == symbmask_t.MASK_PropertySymbol && !(_pCurrentSym is IndexerSymbol)) { // Get the next symbol. return false; } // If our arity is non-0, we must match arity with this symbol. if (_nArity > 0) { if (_mask == symbmask_t.MASK_MethodSymbol && ((MethodSymbol)_pCurrentSym).typeVars.Count != _nArity) { return false; } } // If this guy's not callable, no good. if (!ExpressionBinder.IsMethPropCallable(_pCurrentSym, (_flags & EXPRFLAG.EXF_USERCALLABLE) != 0)) { return false; } // Check access. if (!GetSemanticChecker().CheckAccess(_pCurrentSym, _pCurrentType, _pContext, _pQualifyingType)) { // Sym is not accessible. However, if we're allowing inaccessible, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsInaccessible = true; } else { return false; } } // Check bogus. if (CSemanticChecker.CheckBogus(_pCurrentSym)) { // Sym is bogus, but if we're allow it, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsBogus = true; } else { return false; } } return _bIsCheckingInstanceMethods; } private bool FindNextMethod() { while (true) { if (_pCurrentSym == null) { _pCurrentSym = GetSymbolLoader().LookupAggMember( _pName, _pCurrentType.getAggregate(), _mask) as MethodOrPropertySymbol; } else { _pCurrentSym = SymbolLoader.LookupNextSym( _pCurrentSym, _pCurrentType.getAggregate(), _mask) as MethodOrPropertySymbol; } // If we couldn't find a sym, we look up the type chain and get the next type. if (_pCurrentSym == null) { if (_bIsCheckingInstanceMethods) { if (!FindNextTypeForInstanceMethods() && _bcanIncludeExtensionsInResults) { // We didn't find any more instance methods, set us into extension mode. _bIsCheckingInstanceMethods = false; } else if (_pCurrentType == null && !_bcanIncludeExtensionsInResults) { return false; } else { // Found an instance method. continue; } } continue; } // Note that we do not filter the current symbol for the user. They must do that themselves. // This is because for instance, BindGrpToArgs wants to filter on arguments before filtering // on bogosity. // If we're here, we're good to go. break; } return true; } private bool FindNextTypeForInstanceMethods() { // Otherwise, search through other types listed as well as our base class. if (_pContainingTypes.Count > 0) { if (_nCurrentTypeCount >= _pContainingTypes.Count) { // No more types to check. _pCurrentType = null; } else { _pCurrentType = _pContainingTypes[_nCurrentTypeCount++] as AggregateType; } } else { // We have no more types to consider, so check out the base class. _pCurrentType = _pCurrentType.GetBaseClass(); } return _pCurrentType != null; } } } }
#region copyright // Copyright (c) 2015 Wm. Barrett Simms wbsimms.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 using System.Collections; using System.Threading; namespace GMorse { public class MorseAphabet { Hashtable alphabet = new Hashtable(); private Gadgeteer.SocketInterfaces.DigitalOutput signalOutput; private int delayInterval = 500; public MorseAphabet(Gadgeteer.SocketInterfaces.DigitalOutput output, int dotLength) { this.signalOutput = output; this.delayInterval = dotLength; } public void SendMessage(string message) { foreach (char c in message.ToCharArray()) { if (c == ' ') { WordEnd(); continue; } PlayCode(c); LetterEnd(); } FullStop(); } public void PlayCode(char character) { switch (character.ToLower()) { case 'a': Dot();Dash();return; case 'b': Dash();Dot();Dot();Dot();return; case 'c': Dash();Dot();Dash();Dot();return; case 'd': Dash();Dot();Dot(); return; case 'e': Dot(); return; case 'f': Dot();Dot();Dash();Dot(); return; case 'g': Dash();Dash();Dot(); return; case 'h': Dot();Dot();Dot();Dot(); return; case 'i': Dot();Dot(); return; case 'j': Dot();Dash();Dash(); Dash(); return; case 'k': Dash();Dot();Dash(); return; case 'l': Dot();Dash();Dot();Dot(); return; case 'm': Dash();Dash(); return; case 'n': Dash();Dot(); return; case 'o': Dash();Dash();Dash(); return; case 'p': Dot();Dash();Dash();Dot(); return; case 'q': Dash();Dash();Dot();Dash(); return; case 'r': Dot(); Dash();Dot(); return; case 's': Dot();Dot();Dot(); return; case 't': Dash(); return; case 'u': Dot();Dot();Dash(); return; case 'v': Dot();Dot();Dot();Dash(); return; case 'w': Dot();Dash();Dash(); return; case 'x': Dash();Dot();Dot();Dash(); return; case 'y': Dash();Dot();Dash();Dash(); return; case 'z': Dash();Dash();Dot();Dot(); return; case '1': Dot();Dash();Dash();Dash();Dash(); return; case '2': Dot();Dot();Dash();Dash();Dash(); return; case '3': Dot();Dot();Dot();Dash();Dash(); return; case '4': Dot();Dot();Dot();Dot(); Dash(); return; case '5': Dot();Dot();Dot();Dot();Dot(); return; case '6': Dash();Dot();Dot();Dot();Dot(); return; case '7': Dash();Dash();Dot();Dot();Dot(); return; case '8': Dash();Dash();Dash();Dot();Dot(); return; case '9': Dash();Dash();Dash();Dash();Dot(); return; case '0': Dash();Dash();Dash();Dash();Dash(); return; case ',': Dash();Dash();Dot();Dot();Dash();Dash(); return; case '?': Dot();Dot();Dash();Dash();Dot();Dot();return; default: return; } } private void Dot() { signalOutput.Write(true); Thread.Sleep(delayInterval); signalOutput.Write(false); Thread.Sleep(delayInterval); } private void Dash() { signalOutput.Write(true); Thread.Sleep(delayInterval * 3); signalOutput.Write(false); Thread.Sleep(delayInterval); } private void LetterEnd() { Thread.Sleep(delayInterval * 3); } private void WordEnd() { Thread.Sleep(delayInterval * 7); } private void FullStop() { Dot(); Dash(); Dot(); Dash(); Dot(); Dash(); } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2014 Oleg Shilo 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 Licence... using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using IO = System.IO; using Path = System.IO.Path; #pragma warning disable S2223 // Non-constant static fields should not be visible namespace WixSharp { /// <summary> /// Controls activation of the Wix# compiler features. /// </summary> public enum CompilerSupportState { /// <summary> /// The feature will be enabled automatically when needed /// </summary> [Obsolete(message: "This value is no longer used by any of the compiler features. " + "Use `CompilerSupportState.Enabled` instead.", error: false)] Automatic = 0, /// <summary> /// The feature will be enabled /// </summary> Enabled = 0, /// <summary> /// The feature will be disabled /// </summary> Disabled = 1 } /// <summary> /// Automatically insert elements required for satisfy odd MSI restrictions. /// <para>- You must set KeyPath you install in the user profile.</para> /// <para>- You must use a registry key under HKCU as component's KeyPath, not a file. </para> /// <para>- The Component element cannot have multiple key path set. </para> /// <para>- The project must have at least one directory element. </para> /// <para>- All directories installed in the user profile must have corresponding RemoveDirectory /// elements. </para> /// <para>...</para> /// <para> /// The MSI always wants registry keys as the key paths for per-user components. /// It has to do with the way profiles work with advertised content in enterprise deployments. /// The fact that you do not want to install any registry doesn't matter. MSI is the boss. /// </para> /// <para>The following link is a good example of the technique: /// http://stackoverflow.com/questions/16119708/component-testcomp-installs-to-user-profile-it-must-use-a-registry-key-under-hk</para> /// </summary> public static class AutoElements { /// <summary> /// Controls automatic insertion of CreateFolder and RemoveFolder for the directories containing no files. /// Required for: NativeBootstrapper, EmbeddedMultipleActions, EmptyDirectories, InstallDir, Properties, /// ReleaseFolder, Shortcuts and WildCardFiles samples. /// </summary> public static CompilerSupportState SupportEmptyDirectories = CompilerSupportState.Enabled; /// <summary> /// Disables automatic insertion of <c>KeyPath=yes</c> attribute for the Component element. /// Required for: NativeBootstrapper, EmbeddedMultipleActions, EmptyDirectories, InstallDir, Properties, /// ReleaseFolder, Shortcuts and WildCardFiles samples. /// <para>Can also be managed by disabling ICE validation via Light.exe command line arguments.</para> /// <para> /// This flag is a lighter alternative of DisableAutoCreateFolder. /// <para> /// See: http://stackoverflow.com/questions/10358989/wix-using-keypath-on-components-directories-files-registry-etc-etc /// </para> /// for some background info. /// </para> /// </summary> public static bool DisableAutoKeyPath = false; /// <summary> /// Enables expanding Wix environment constants in <see cref="WixSharp.RegValue.Value"/>. /// <para>This flag was introduced as a fall back mechanism for legacy action of expanding Wix /// constants in registry values. This work around was triggered by issue #774.</para> /// </summary> public static bool ExpandWixConstsInRegValue = false; /// <summary> /// Enables UAC revealer, which is a work around for the MSI limitation/problem around EmbeddedUI UAC prompt. /// <para> The symptom of the problem is the UAC prompt not being displayed during elevation but rather minimized /// on the taskbar. This is caused by the fact the all background applications (including MSI runtime) supposed to /// register the main window for UAC prompt. And, MSI does not do the registration for EmbeddedUI. /// </para> /// <para> See "Use the HWND Property to Be Acknowledged as a Foreground Application" section at /// https://msdn.microsoft.com/en-us/library/bb756922.aspx /// </para> /// </summary> public static bool EnableUACRevealer = true; /// <summary> /// The UAC warning message to be displayed at the start of the actual installation (Progress dialog) /// of the ManagedUI setup. /// <para>The purpose of this message is to draw user attention to the fact that Windows UAC prompt may not /// become visible and instead be minimized on the taskbar. /// </para> /// <remarks> /// Windows prevents UIC prompt from stealing the focus if at the time of elevation user performs /// interaction with other foreground process (application). It is a controversial aspect of Windows /// User Experience that sometimes has undesirable practical implications. /// </remarks> /// </summary> public static string UACWarning = "Please wait for UAC prompt to appear.\r\n\r\nIf it appears minimized then" + " activate it from the taskbar."; /// <summary> /// Forces all <see cref="T:WixSharp.Condition"/> values to be always encoded as CDATA. /// </summary> public static bool ForceCDataForConditions = false; /// <summary> /// Flag indicating if the legacy algorithm should be used for handling setups with no directories /// to be installed but only non-file system components (e.g. RegKey, User, Firewall exceptions). /// <para>The algorithm used in early versions of WixSharp (legacy algorithm) injects a dummy /// directory into the setup definition so it satisfies the MSI constraint that every component must /// belong to a directory. As many other rules this one has no practical value and rather reflection /// of the outdated (~20 years ago) deployment approaches.</para> /// <para>The current algorithm also ensures the that there is a XML directory to host the components. /// However instead of custom (dummy) directory it inserts 'ProgramFilesFolder'. This way MSI constraint /// is satisfied and yet there is no impact on the target file system.</para> /// </summary> public static bool LegacyDummyDirAlgorithm = false; /// <summary> /// Enables scheduling deferred actions just after their corresponding /// "SetDeferredActionProperties" custom action. Enabled by default. /// </summary> public static bool ScheduleDeferredActionsAfterTunnellingTheirProperties = true; /// <summary> /// Disables automatic insertion of user profile registry elements. /// Required for: AllInOne, ConditionalInstallation, CustomAttributes, ReleaseFolder, Shortcuts, /// Shortcuts (advertised), Shortcuts-2, WildCardFiles samples. /// <para>Can also be managed by disabling ICE validation via Light.exe command line arguments.</para> /// </summary> public static bool DisableAutoUserProfileRegistry = false; static void InsertRemoveFolder(XElement xDir, XElement xComponent, string when = "uninstall") { if (!xDir.IsUserProfileRoot()) { string dirId = xDir.Attribute("Id").Value; bool alreadyPresent = xComponent.Elements("RemoveFolder") .Where(x => x.HasAttribute("Id", dirId)) .Any(); if (!alreadyPresent) xComponent.Add(new XElement("RemoveFolder", new XAttribute("Id", xDir.Attribute("Id").Value), new XAttribute("On", when))); } } internal static XElement InsertUserProfileRemoveFolder(this XElement xComponent) { var xDir = xComponent.Parent("Directory"); if (!xDir.Descendants("RemoveFolder").Any() && !xDir.IsUserProfileRoot()) xComponent.Add(new XElement("RemoveFolder", new XAttribute("Id", xDir.Attribute("Id").Value), new XAttribute("On", "uninstall"))); return xComponent; } static void InsertCreateFolder(XElement xComponent) { //prevent adding more than 1 CreateFolder elements - elements that don't specify @Directory if (xComponent.Elements("CreateFolder").All(element => element.HasAttribute("Directory"))) xComponent.Add(new XElement("CreateFolder")); EnsureKeyPath(xComponent); } static void EnsureKeyPath(XElement xComponent) { if (!DisableAutoKeyPath) { // A component must have KeyPath set on itself or on a single (just one) nested element. // may conflict with the folder removal (https://github.com/oleg-shilo/wixsharp/issues/123). if (!xComponent.HasKeyPathElements()) xComponent.SetAttribute("KeyPath=yes"); } } internal static string FindInstallDirId(this XElement product) { if (product.FindAll("Directory") .Any(p => p.HasAttribute("Id", Compiler.AutoGeneration.InstallDirDefaultId))) return Compiler.AutoGeneration.InstallDirDefaultId; return null; } internal static bool HasKeyPathElements(this XElement xComponent) { return xComponent.Descendants() .Where(e => e.HasKeyPathSet()) .Any(); } internal static XElement ClearKeyPath(this XElement element) { return element.SetAttribute("KeyPath", null); } internal static bool HasKeyPathSet(this XElement element) { var attr = element.Attribute("KeyPath"); if (attr != null && attr.Value == "yes") return true; return false; } internal static XElement InsertUserProfileRegValue(this XElement xComponent) { //UserProfileRegValue has to be a KeyPath fo need to remove any KeyPath on other elements var keyPathes = xComponent.Descendants() .ForEach(e => e.ClearKeyPath()); xComponent.ClearKeyPath(); xComponent.Add( new XElement("RegistryKey", new XAttribute("Root", "HKCU"), new XAttribute("Key", @"Software\WixSharp\Used"), new XElement("RegistryValue", new XAttribute("Value", "0"), new XAttribute("Type", "string"), new XAttribute("KeyPath", "yes")))); return xComponent; } static void InsertDummyUserProfileRegistry(XElement xComponent) { if (!DisableAutoUserProfileRegistry) { InsertUserProfileRegValue(xComponent); } } static void SetFileKeyPath(XElement element, bool isKeyPath = true) { if (element.Attribute("KeyPath") == null) element.Add(new XAttribute("KeyPath", isKeyPath ? "yes" : "no")); } static bool ContainsDummyUserProfileRegistry(this XElement xComponent) { return (from e in xComponent.Elements("RegistryKey") where e.Attribute("Key") != null && e.Attribute("Key").Value == @"Software\WixSharp\Used" select e).Count() != 0; } static bool ContainsAnyRemoveFolder(this XElement xDir) { //RemoveFolder is expected to be enclosed in Component and appear only once per Directory element return xDir.Elements("Component") .SelectMany(c => c.Elements("RemoveFolder")) .Any(); } static bool ContainsFiles(this XElement xComp) { return xComp.Elements("File").Any(); } static bool ContainsFilesOrRegistries(this XElement xComp) { return xComp.Elements("File").Any() || xComp.Elements("RegistryKey").Any(); } static bool ContainsComponents(this XElement xDir) { return xDir.Elements("Component").Any(); } static bool ContainsAdvertisedShortcuts(this XElement xComp) { var advertisedShortcuts = from e in xComp.Descendants("Shortcut") where e.Attribute("Advertise") != null && e.Attribute("Advertise").Value == "yes" select e; return (advertisedShortcuts.Count() != 0); } static bool ContainsNonAdvertisedShortcuts(this XElement xComp) { var nonAdvertisedShortcuts = from e in xComp.Descendants("Shortcut") where e.Attribute("Advertise") == null || e.Attribute("Advertise").Value == "no" select e; return (nonAdvertisedShortcuts.Count() != 0); } static XElement CreateComponentFor(this XDocument doc, XElement xDir) { string compId = xDir.Attribute("Id").Value; XElement xComponent = xDir.AddElement( new XElement("Component", new XAttribute("Id", compId), new XAttribute("Guid", WixGuid.NewGuid(compId)))); foreach (XElement xFeature in doc.Root.Descendants("Feature")) xFeature.Add(new XElement("ComponentRef", new XAttribute("Id", xComponent.Attribute("Id").Value))); return xComponent; } private static string[] GetUserProfileFolders() { return new[] { "ProgramMenuFolder", "AppDataFolder", "LocalAppDataFolder", "TempFolder", "PersonalFolder", "DesktopFolder", "StartupFolder" }; } static bool InUserProfile(this XElement xDir) { string[] userProfileFolders = GetUserProfileFolders(); XElement xParentDir = xDir; do { if (xParentDir.Name == "Directory") { var attrName = xParentDir.Attribute("Name").Value; if (userProfileFolders.Contains(attrName)) return true; } xParentDir = xParentDir.Parent; } while (xParentDir != null); return false; } static bool IsUserProfileRoot(this XElement xDir) { string[] userProfileFolders = GetUserProfileFolders(); return userProfileFolders.Contains(xDir.Attribute("Name").Value); } internal static void InjectShortcutIcons(XDocument doc) { var shortcuts = from s in doc.Root.Descendants("Shortcut") where s.HasAttribute("Icon") select s; int iconIndex = 1; var icons = new Dictionary<string, string>(); foreach (var iconFile in (from s in shortcuts select s.Attribute("Icon").Value).Distinct()) { icons.Add(iconFile, "IconFile" + (iconIndex++) + "_" + IO.Path.GetFileName(iconFile).Expand()); } foreach (XElement shortcut in shortcuts) { string iconFile = shortcut.Attribute("Icon").Value; string iconId = icons[iconFile]; shortcut.Attribute("Icon").Value = iconId; } XElement product = doc.Root.Select("Product"); foreach (string file in icons.Keys) product.AddElement( new XElement("Icon", new XAttribute("Id", icons[file]), new XAttribute("SourceFile", file))); } static void InjectPlatformAttributes(XDocument doc) { var is64BitPlatform = doc.Root.Select("Product/Package").HasAttribute("Platform", val => val == "x64"); if (is64BitPlatform) { doc.Descendants("Component") .ForEach(comp => { if (!comp.HasAttribute("Win64")) comp.SetAttributeValue("Win64", "yes"); }); } } internal static void ExpandCustomAttributes(XDocument doc, WixProject project) { foreach (XAttribute instructionAttr in doc.Root.Descendants().Select(x => x.Attribute("WixSharpCustomAttributes")).Where(x => x != null)) { XElement sourceElement = instructionAttr.Parent; foreach (string item in instructionAttr.Value.Split(';')) if (item.IsNotEmpty()) { if (!ExpandCustomAttribute(sourceElement, item, project)) { var message = "Cannot resolve custom attribute definition:" + item; if (item.StartsWith("Component:")) message += "\nNote, some Wix elements may not be contained by 'Component' elements (e.g. 'CloseApplication'). " + "Thus attempt to set parent component attribute will always fail.\n"; throw new ApplicationException(message); } } instructionAttr.Remove(); } } static Func<XElement, string, WixProject, bool> ExpandCustomAttribute = DefaultExpandCustomAttribute; static bool DefaultExpandCustomAttribute(XElement source, string item, WixProject project) { var attrParts = item.Split(new[] { '=' }, 2, StringSplitOptions.None); // {dep}ProductKey=12345 vs // Component:{dep}ProductKey=12345 vs // {http://schemas.microsoft.com/wix/BalExtension}Overridable=yes" // Component:{dep}elementm_Condition=base64:edr34r34r43 // Note the syntax below is not supported: // Component:{http://schemas.microsoft.com/wix/BalExtension}Overridable=yes" if (item.Contains(":{http:") || item.Contains(":{https:")) throw new Exception("Syntax `" + item + "` is not supported.\n" + "Use `parent:{alias}attribute=value` instead and add XML namespace with the alias.\n" + "For example: `project.IncludeWixExtension(\"WixDependencyExtension.dll\", \"dep\", expectedNamespace);`"); string[] keyParts; if (item.StartsWith("{")) item = ":" + item; var nameSpec = attrParts.First(); if (nameSpec.StartsWith("{")) keyParts = new[] { nameSpec }; // name specification does not have any `parent prefix` else keyParts = nameSpec.Split(':'); // here it does string element = keyParts.First(); string key = keyParts.Last(); string value = attrParts.Last(); if (element == "Component") { XElement destElement = source.Parent("Component"); if (destElement != null) { if (key == "element_Condition") { var name = "Condition"; var data = value; if (data.StartsWith("base64_")) data = data.Replace("base64_", "").Base64Decode(); destElement.AddElement(name, null, data); } else { destElement.SetAttribute(key, value); } return true; } } if (element == "Custom" && source.Name.LocalName == "CustomAction") { string id = source.Attribute("Id").Value; var elements = source.Document.Descendants("Custom").Where(e => e.Attribute("Action").Value == id); if (elements.Any()) { elements.ForEach(e => e.SetAttribute(key, value)); return true; } } if (key.StartsWith("{")) { source.SetAttribute(key, value); return true; } if (key.StartsWith("xml_include")) { var parts = value.Split('|'); string parentName = parts[0]; string xmlFile = parts[1]; var placement = source; if (!parentName.IsEmpty()) placement = source.Parent(parentName); if (placement != null) { string xmlFilePath; // Strangely enough all relative paths in the wxs are resolved with respect to the // process CurrrentDir but includes it is resolved with respect to the location of the // wxs file containing the include statement. Thus if there is any discrepancy between // source and output dirs then it is safer to use absolute paths instead of relative. if (!xmlFile.IsAbsolutePath() && project.SourceBaseDir != project.OutDir) xmlFilePath = project.SourceBaseDir.ToAbsolutePath().PathCombine(xmlFile); else xmlFilePath = xmlFile; placement.Add(new XProcessingInstruction("include", xmlFilePath)); return true; } } return false; } static void InsertEmptyComponentsInParentDirectories(XDocument doc, XElement item) { XElement parent = item.Parent("Directory"); while (parent != null) { if (parent.Element("Component") == null) { var dirId = parent.Attribute("Id")?.Value; if (Compiler.EnvironmentConstantsMapping.ContainsValue(dirId)) break; //stop when reached start of user defined subdirs chain: TARGETDIR/ProgramFilesFolder!!!/ProgramFilesFolder.Company/INSTALLDIR //just folder with nothing in it but not the last leaf doc.CreateComponentFor(parent); } parent = parent.Parent("Directory"); } } static void CreateEmptyComponentsInDirectoriesToRemove(XDocument doc) { XElement product = doc.Root.Select("Product"); // Create new empty components in parent directories of components with no files or registry var dirsWithNoFilesOrRegistryComponents = product.Descendants("Directory") .SelectMany(x => x.Elements("Component")) .Where(e => !e.ContainsFilesOrRegistries()) .Select(x => x.Parent("Directory")); foreach (var item in dirsWithNoFilesOrRegistryComponents) { InsertEmptyComponentsInParentDirectories(doc, item); } } internal static void HandleEmptyDirectories(XDocument doc) { XElement product = doc.Root.Select("Product"); var dummyDirs = product.Descendants("Directory") .SelectMany(x => x.Elements("Component")) .Where(e => e.HasAttribute("Id", v => v.EndsWith(".EmptyDirectory"))) .Select(x => x.Parent("Directory")).ToArray(); if (SupportEmptyDirectories == CompilerSupportState.Enabled) { if (dummyDirs.Any()) { foreach (var item in dummyDirs) { InsertEmptyComponentsInParentDirectories(doc, item); } } foreach (XElement xDir in product.Descendants("Directory").ToArray()) { var dirComponents = xDir.Elements("Component"); if (dirComponents.Any()) { var componentsWithNoFiles = dirComponents.Where(x => !x.ContainsFiles()).ToArray(); //'EMPTY DIRECTORY' support processing section foreach (XElement item in componentsWithNoFiles) { // Ridiculous MSI constraints: // * you cannot install empty folders // - workaround is to insert empty component with CreateFolder element // * if Component+CreateFolder element is inserted the folder will not be removed on uninstall // - workaround is to insert RemoveFolder element in to empty component as well // * if Component+CreateFolder+RemoveFolder elements are placed in a dummy component to handle an empty folder // any parent folder with no files/components will not be removed on uninstall. // - workaround is to insert Component+Create+RemoveFolder elements in any parent folder with no files. // // OMG!!!! If it is not over-engineering I don't know what is. bool oldAlgorithm = false; if (!oldAlgorithm) { //current approach InsertCreateFolder(item); if (!xDir.ContainsAnyRemoveFolder()) InsertRemoveFolder(xDir, item, "uninstall"); } else { //old approach if (!item.Attribute("Id").Value.EndsWith(".EmptyDirectory")) InsertCreateFolder(item); else if (!xDir.ContainsAnyRemoveFolder()) InsertRemoveFolder(xDir, item, "uninstall"); //to keep WiX/compiler happy and allow removal of the dummy directory } } } } } } internal static void InjectAutoElementsHandler(XDocument doc, Project project) { ExpandCustomAttributes(doc, project); InjectShortcutIcons(doc); HandleEmptyDirectories(doc); XElement product = doc.Root.Select("Product"); int? absPathCount = null; foreach (XElement dir in product.Element("Directory").Elements("Directory")) { XElement installDir = dir; XAttribute installDirName = installDir.Attribute("Name"); if (IO.Path.IsPathRooted(installDirName.Value)) { string absolutePath = installDirName.Value; if (dir == product.Element("Directory").Elements("Directory").First()) //only for the first root dir { //ManagedUI will need some hint on the install dir as it cannot rely on the session action (e.g. Set_INSTALLDIR_AbsolutePath) //because it is running outside of the sequence and analyses the tables directly for the INSTALLDIR product.AddElement("Property", "Id=INSTALLDIR_ABSOLUTEPATH; Value=" + absolutePath); } installDirName.Value = $"ABSOLUTEPATH{absPathCount}"; //<SetProperty> for INSTALLDIR is an attractive approach but it doesn't allow conditional setting of 'ui' and 'execute' as required depending on UI level // it is ether hard-coded 'both' or hard coded-both 'ui' or 'execute' // <SetProperty Id="INSTALLDIR" Value="C:\My Company\MyProduct" Sequence="both" Before="AppSearch"> string actualDirName = installDir.Attribute("Id").Value; string customAction = $"Set_DirAbsolutePath{absPathCount}"; product.Add(new XElement("CustomAction", new XAttribute("Id", customAction), new XAttribute("Property", actualDirName), new XAttribute("Value", absolutePath))); product.SelectOrCreate("InstallExecuteSequence").Add( new XElement("Custom", $"(NOT Installed) AND (UILevel < 5) AND ({actualDirName} = ABSOLUTEPATH{absPathCount})", new XAttribute("Action", customAction), new XAttribute("Before", "AppSearch"))); product.SelectOrCreate("InstallUISequence").Add( new XElement("Custom", $"(NOT Installed) AND (UILevel = 5) AND ({actualDirName} = ABSOLUTEPATH{absPathCount})", new XAttribute("Action", customAction), new XAttribute("Before", "AppSearch"))); if (absPathCount == null) absPathCount = 0; absPathCount++; } } CreateEmptyComponentsInDirectoriesToRemove(doc); foreach (XElement xDir in product.Descendants("Directory").ToArray()) { var dirComponents = xDir.Elements("Component").ToArray(); if (dirComponents.Any()) { var componentsWithNoFilesOrRegistry = dirComponents.Where(x => !x.ContainsFilesOrRegistries()).ToArray(); foreach (XElement item in componentsWithNoFilesOrRegistry) { //if (!item.Attribute("Id").Value.EndsWith(".EmptyDirectory")) EnsureKeyPath(item); if (!xDir.ContainsAnyRemoveFolder()) InsertRemoveFolder(xDir, item, "uninstall"); //to keep WiX/compiler happy and allow removal of the dummy directory } } foreach (XElement xComp in dirComponents) { if (xDir.InUserProfile()) { if (!xDir.ContainsAnyRemoveFolder()) InsertRemoveFolder(xDir, xComp); if (!xComp.ContainsDummyUserProfileRegistry()) InsertDummyUserProfileRegistry(xComp); } else { if (xComp.ContainsNonAdvertisedShortcuts()) if (!xComp.ContainsDummyUserProfileRegistry()) InsertDummyUserProfileRegistry(xComp); } foreach (XElement xFile in xComp.Elements("File")) if (xFile.ContainsAdvertisedShortcuts() && !xComp.ContainsDummyUserProfileRegistry()) SetFileKeyPath(xFile); } if (!xDir.ContainsComponents() && xDir.InUserProfile()) { if (!xDir.IsUserProfileRoot()) { XElement xComp1 = doc.CreateComponentFor(xDir); if (!xDir.ContainsAnyRemoveFolder()) InsertRemoveFolder(xDir, xComp1); if (!xComp1.ContainsDummyUserProfileRegistry()) InsertDummyUserProfileRegistry(xComp1); } } } //Not a property Id as MSI requires Predicate<string> needsProperty = value => value.Contains("\\") || value.Contains("//") || value.Contains("%") || value.Contains("[") || value.Contains("]"); foreach (XElement xShortcut in product.Descendants("Shortcut")) { if (xShortcut.HasAttribute("WorkingDirectory", x => needsProperty(x))) { string workingDirectory = xShortcut.Attribute("WorkingDirectory").Value; if (workingDirectory.StartsWith("%") && workingDirectory.EndsWith("%")) //%INSTALLDIR% { workingDirectory = workingDirectory.ExpandWixEnvConsts(); xShortcut.SetAttributeValue("WorkingDirectory", workingDirectory.Replace("%", "")); } else if (workingDirectory.StartsWith("[") && workingDirectory.EndsWith("]")) //[INSTALLDIR] { xShortcut.SetAttributeValue("WorkingDirectory", workingDirectory.Replace("[", "").Replace("]", "")); } else { string workinDirPath = workingDirectory.ReplaceWixSharpEnvConsts(); XElement existingProperty = product.Descendants("Property") .FirstOrDefault(p => p.HasAttribute("Value", workingDirectory)); if (existingProperty != null) { xShortcut.SetAttributeValue("WorkingDirectory", existingProperty.Attribute("Id").Value); } else { string propId = xShortcut.Attribute("Id").Value + ".WorkDir"; product.AddElement("Property", "Id=" + propId + "; Value=" + workinDirPath); xShortcut.SetAttributeValue("WorkingDirectory", propId); } } } } InjectPlatformAttributes(doc); } internal static void NormalizeFilePaths(XDocument doc, string sourceBaseDir, bool emitRelativePaths) { string rootDir = sourceBaseDir; if (rootDir.IsEmpty()) rootDir = Environment.CurrentDirectory; rootDir = IO.Path.GetFullPath(rootDir); Action<IEnumerable<XElement>, string> normalize = (elements, attributeName) => { elements.Where(e => e.HasAttribute(attributeName)) .ForEach(e => { var attr = e.Attribute(attributeName); if (emitRelativePaths) attr.Value = Utils.MakeRelativeTo(attr.Value, rootDir); else attr.Value = Path.GetFullPath(attr.Value); }); }; normalize(doc.Root.FindAll("Icon"), "SourceFile"); normalize(doc.Root.FindAll("File"), "Source"); normalize(doc.Root.FindAll("Merge"), "SourceFile"); normalize(doc.Root.FindAll("Binary"), "SourceFile"); normalize(doc.Root.FindAll("EmbeddedUI"), "SourceFile"); normalize(doc.Root.FindAll("Payload"), "SourceFile"); normalize(doc.Root.FindAll("MsiPackage"), "SourceFile"); normalize(doc.Root.FindAll("ExePackage"), "SourceFile"); } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal sealed partial class EventHookupSessionManager { /// <summary> /// A session begins when an '=' is typed after a '+' and requires determining whether the /// += is being used to add an event handler to an event. If it is, then we also determine /// a candidate name for the event handler. /// </summary> internal class EventHookupSession : ForegroundThreadAffinitizedObject { public readonly Task<string> GetEventNameTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly ITrackingPoint _trackingPoint; private readonly ITrackingSpan _trackingSpan; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; // For testing purposes only! Should always be null except in tests. internal Mutex TESTSessionHookupMutex = null; public ITrackingPoint TrackingPoint { get { AssertIsForeground(); return _trackingPoint; } } public ITrackingSpan TrackingSpan { get { AssertIsForeground(); return _trackingSpan; } } public ITextView TextView { get { AssertIsForeground(); return _textView; } } public ITextBuffer SubjectBuffer { get { AssertIsForeground(); return _subjectBuffer; } } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } public EventHookupSession( EventHookupSessionManager eventHookupSessionManager, EventHookupCommandHandler commandHandler, ITextView textView, ITextBuffer subjectBuffer, IAsynchronousOperationListener asyncListener, Mutex testSessionHookupMutex) { AssertIsForeground(); _cancellationTokenSource = new CancellationTokenSource(); _textView = textView; _subjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { var position = textView.GetCaretPoint(subjectBuffer).Value.Position; _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, _cancellationTokenSource.Token), _cancellationTokenSource.Token, TaskScheduler.Default); var continuedTask = this.GetEventNameTask.SafeContinueWith(t => { AssertIsForeground(); if (t.Result != null) { commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); } }, _cancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundThreadAffinitizedObject.CurrentForegroundThreadData.TaskScheduler); continuedTask.CompletesAsyncOperation(asyncToken); } else { _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); this.GetEventNameTask = SpecializedTasks.Default<string>(); eventHookupSessionManager.CancelAndDismissExistingSessions(); } } private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); // For test purposes only! if (TESTSessionHookupMutex != null) { TESTSessionHookupMutex.WaitOne(); TESTSessionHookupMutex.ReleaseMutex(); } using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) { var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); if (plusEqualsToken == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); if (eventSymbol == null) { return null; } return GetEventHandlerName(eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>()); } } private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() != SyntaxKind.PlusEqualsToken) { return null; } if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) { return null; } return token; } private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken == null) { return null; } var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; if (symbol == null) { return null; } return symbol as IEventSymbol; } private string GetEventHandlerName(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var basename = string.Format("{0}_{1}", GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService), eventSymbol.Name); basename = basename.ToPascalCase(trimLeadingTypePrefix: false); var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); return NameGenerator.EnsureUniqueness(basename, reservedNames); } /// <summary> /// Take another look at the LHS of the += node -- we need to figure out a default name /// for the event handler, and that's usually based on the object (which is usually a /// field of 'this', but not always) to which the event belongs. So, if the event is /// something like 'button1.Click' or 'this.listBox1.Select', we want the names /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use /// the name of this class, as we do if we can't make any sense out of the parse tree. /// </summary> private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; var memberAccessExpression = parentToken.Left as MemberAccessExpressionSyntax; if (memberAccessExpression != null) { // This is expected -- it means the last thing is(probably) the event name. We // already have that in eventSymbol. What we need is the LHS of that dot. var lhs = memberAccessExpression.Expression; var lhsMemberAccessExpression = lhs as MemberAccessExpressionSyntax; if (lhsMemberAccessExpression != null) { // Okay, cool. The name we're after is in the RHS of this dot. return lhsMemberAccessExpression.Name.ToString(); } var lhsNameSyntax = lhs as NameSyntax; if (lhsNameSyntax != null) { // Even easier -- the LHS of the dot is the name itself return lhsNameSyntax.ToString(); } } // If we didn't find an object name above, then the object name is the name of this class. // Note: For generic, it's ok(it's even a good idea) to exclude type variables, // because the name is only used as a prefix for the method name. var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( semanticModel.SyntaxTree.GetRoot(), plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; return typeDeclaration != null ? typeDeclaration.Identifier.Text : eventSymbol.ContainingType.Name; } } } }
using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace VulkanCore { /// <summary> /// Structure specifying a two-dimensional extent. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Extent2D : IEquatable<Extent2D> { /// <summary> /// A special valued <see cref="Extent3D"/>. /// </summary> public static readonly Extent2D WholeSize = new Extent2D(~0, ~0); /// <summary> /// An <see cref="Extent3D"/> with all of its components set to zero. /// </summary> public static readonly Extent2D Zero = new Extent2D(0, 0); /// <summary> /// The width component of the extent. /// </summary> public int Width; /// <summary> /// The height component of the extent. /// </summary> public int Height; /// <summary> /// Initializes a new instance of <see cref="Extent2D"/> structure. /// </summary> /// <param name="width">The width component of the extent.</param> /// <param name="height">The height component of the extent.</param> public Extent2D(int width, int height) { Width = width; Height = height; } /// <summary> /// Returns a string representing this <see cref="Extent2D"/> instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() => ToString(CultureInfo.CurrentCulture); /// <summary> /// Returns a string representing this <see cref="Extent2D"/> instance, using the specified /// format to format individual elements and the given <paramref name="formatProvider"/>. /// </summary> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(IFormatProvider formatProvider) { var sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(Width.ToString(formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(Height.ToString(formatProvider)); sb.Append('>'); return sb.ToString(); } /// <summary> /// Determines whether the specified <see cref="Extent2D"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="Extent2D"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Extent2D"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(ref Extent2D other) => other.Width == Width && other.Height == Height; /// <summary> /// Determines whether the specified <see cref="Extent2D"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="Extent2D"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Extent2D"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Extent2D other) => Equals(ref other); /// <summary> /// Determines whether the specified <see cref="object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) => obj is Extent2D && Equals((Extent2D)obj); /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hashCode = Width.GetHashCode(); hashCode = (hashCode * 397) ^ Height.GetHashCode(); return hashCode; } } /// <summary> /// Returns a boolean indicating whether the two given extents are equal. /// </summary> /// <param name="left">The first extent to compare.</param> /// <param name="right">The second extent to compare.</param> /// <returns><c>true</c> if the extents are equal; <c>false</c> otherwise.</returns> public static bool operator ==(Extent2D left, Extent2D right) => left.Equals(ref right); /// <summary> /// Returns a boolean indicating whether the two given extents are not equal. /// </summary> /// <param name="left">The first extent to compare.</param> /// <param name="right">The second extent to compare.</param> /// <returns> /// <c>true</c> if the extents are not equal; <c>false</c> if they are equal. /// </returns> public static bool operator !=(Extent2D left, Extent2D right) => !left.Equals(ref right); } /// <summary> /// Structure specifying a three-dimensional extent. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Extent3D : IEquatable<Extent3D> { /// <summary> /// A special valued <see cref="Extent3D"/>. /// </summary> public static readonly Extent3D WholeSize = new Extent3D(~0, ~0, ~0); /// <summary> /// An <see cref="Extent3D"/> with all of its components set to zero. /// </summary> public static readonly Extent3D Zero = new Extent3D(0, 0, 0); /// <summary> /// The width component of the extent. /// </summary> public int Width; /// <summary> /// The height component of the extent. /// </summary> public int Height; /// <summary> /// The depth component of the extent. /// </summary> public int Depth; /// <summary> /// Initializes a new instance of <see cref="Extent3D"/> structure. /// </summary> /// <param name="width">The width component of the extent.</param> /// <param name="height">The height component of the extent.</param> /// <param name="depth">The depth component of the extent.</param> public Extent3D(int width, int height, int depth) { Width = width; Height = height; Depth = depth; } /// <summary> /// Returns a string representing this <see cref="Extent3D"/> instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() => ToString(CultureInfo.CurrentCulture); /// <summary> /// Returns a string representing this <see cref="Extent3D"/> instance, using the specified /// format to format individual elements and the given <paramref name="formatProvider"/>. /// </summary> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(IFormatProvider formatProvider) { var sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(Width.ToString(formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(Height.ToString(formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(Depth.ToString(formatProvider)); sb.Append('>'); return sb.ToString(); } /// <summary> /// Determines whether the specified <see cref="Extent3D"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="Extent3D"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Extent3D"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(ref Extent3D other) => other.Width == Width && other.Height == Height && other.Depth == Depth; /// <summary> /// Determines whether the specified <see cref="Extent3D"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="Extent3D"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Extent3D"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Extent3D other) => Equals(ref other); /// <summary> /// Determines whether the specified <see cref="object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) => obj is Extent3D && Equals((Extent3D)obj); /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hashCode = Width.GetHashCode(); hashCode = (hashCode * 397) ^ Height.GetHashCode(); return hashCode; } } /// <summary> /// Returns a boolean indicating whether the two given extents are equal. /// </summary> /// <param name="left">The first extent to compare.</param> /// <param name="right">The second extent to compare.</param> /// <returns><c>true</c> if the extents are equal; <c>false</c> otherwise.</returns> public static bool operator ==(Extent3D left, Extent3D right) => left.Equals(ref right); /// <summary> /// Returns a boolean indicating whether the two given extents are not equal. /// </summary> /// <param name="left">The first extent to compare.</param> /// <param name="right">The second extent to compare.</param> /// <returns> /// <c>true</c> if the extents are not equal; <c>false</c> if they are equal. /// </returns> public static bool operator !=(Extent3D left, Extent3D right) => !left.Equals(ref right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Dynamic; using System.Linq; using IronPython.Runtime.Binding; using IronPython.Runtime.Types; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Operations { internal static class PythonTypeOps { private static readonly Dictionary<FieldInfo, PythonTypeSlot> _fieldCache = new Dictionary<FieldInfo, PythonTypeSlot>(); private static readonly Dictionary<BuiltinFunction, BuiltinMethodDescriptor> _methodCache = new Dictionary<BuiltinFunction, BuiltinMethodDescriptor>(); private static readonly Dictionary<BuiltinFunction, ClassMethodDescriptor> _classMethodCache = new Dictionary<BuiltinFunction, ClassMethodDescriptor>(); internal static readonly Dictionary<BuiltinFunctionKey, BuiltinFunction> _functions = new Dictionary<BuiltinFunctionKey, BuiltinFunction>(); private static readonly Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction> _ctors = new Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction>(); private static readonly Dictionary<EventTracker, ReflectedEvent> _eventCache = new Dictionary<EventTracker, ReflectedEvent>(); internal static readonly Dictionary<PropertyTracker, ReflectedGetterSetter> _propertyCache = new Dictionary<PropertyTracker, ReflectedGetterSetter>(); internal static PythonTuple MroToPython(IList<PythonType> types) { List<object> res = new List<object>(types.Count); foreach (PythonType dt in types) { if (dt.UnderlyingSystemType == typeof(ValueType)) continue; // hide value type if(dt.OldClass != null) { res.Add(dt.OldClass); } else { res.Add(dt); } } return PythonTuple.Make(res); } internal static string GetModuleName(CodeContext/*!*/ context, Type type) { Type curType = type; while (curType != null) { string moduleName; if (context.LanguageContext.BuiltinModuleNames.TryGetValue(curType, out moduleName)) { return moduleName; } curType = curType.DeclaringType; } FieldInfo modField = type.GetField("__module__"); if (modField != null && modField.IsLiteral && modField.FieldType == typeof(string)) { return (string)modField.GetRawConstantValue(); } return "__builtin__"; } internal static object CallParams(CodeContext/*!*/ context, PythonType cls, params object[] args\u03c4) { if (args\u03c4 == null) args\u03c4 = ArrayUtils.EmptyObjects; return CallWorker(context, cls, args\u03c4); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, object[] args) { object newObject = PythonOps.CallWithContext(context, GetTypeNew(context, dt), ArrayUtils.Insert<object>(dt, args)); if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Length)) { PythonOps.CallWithContext(context, GetInitMethod(context, dt, newObject), args); AddFinalizer(context, dt, newObject); } return newObject; } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, IDictionary<string, object> kwArgs, object[] args) { object[] allArgs = ArrayOps.CopyArray(args, kwArgs.Count + args.Length); string[] argNames = new string[kwArgs.Count]; int i = args.Length; foreach (KeyValuePair<string, object> kvp in kwArgs) { allArgs[i] = kvp.Value; argNames[i++ - args.Length] = kvp.Key; } return CallWorker(context, dt, new KwCallInfo(allArgs, argNames)); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, KwCallInfo args) { object[] clsArgs = ArrayUtils.Insert<object>(dt, args.Arguments); object newObject = PythonOps.CallWithKeywordArgs(context, GetTypeNew(context, dt), clsArgs, args.Names); if (newObject == null) return null; if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Arguments.Length)) { PythonOps.CallWithKeywordArgs(context, GetInitMethod(context, dt, newObject), args.Arguments, args.Names); AddFinalizer(context, dt, newObject); } return newObject; } /// <summary> /// Looks up __init__ avoiding calls to __getattribute__ and handling both /// new-style and old-style classes in the MRO. /// </summary> private static object GetInitMethod(CodeContext/*!*/ context, PythonType dt, object newObject) { // __init__ is never searched for w/ __getattribute__ for (int i = 0; i < dt.ResolutionOrder.Count; i++) { PythonType cdt = dt.ResolutionOrder[i]; PythonTypeSlot dts; object value; if (cdt.IsOldClass) { if (PythonOps.ToPythonType(cdt) is OldClass oc && oc.TryGetBoundCustomMember(context, "__init__", out value)) { return oc.GetOldStyleDescriptor(context, value, newObject, oc); } // fall through to new-style only case. We might accidently // detect old-style if the user imports a IronPython.NewTypes // type. } if (cdt.TryLookupSlot(context, "__init__", out dts) && dts.TryGetValue(context, newObject, dt, out value)) { return value; } } return null; } private static void AddFinalizer(CodeContext/*!*/ context, PythonType dt, object newObject) { // check if object has finalizer... PythonTypeSlot dummy; if (dt.TryResolveSlot(context, "__del__", out dummy)) { IWeakReferenceable iwr = context.LanguageContext.ConvertToWeakReferenceable(newObject); Debug.Assert(iwr != null); InstanceFinalizer nif = new InstanceFinalizer(context, newObject); iwr.SetFinalizer(new WeakRefTracker(iwr, nif, nif)); } } private static object GetTypeNew(CodeContext/*!*/ context, PythonType dt) { PythonTypeSlot dts; if (!dt.TryResolveSlot(context, "__new__", out dts)) { throw PythonOps.TypeError("cannot create instances of {0}", dt.Name); } object newInst; bool res = dts.TryGetValue(context, dt, dt, out newInst); Debug.Assert(res); return newInst; } internal static bool IsRuntimeAssembly(Assembly assembly) { if (assembly == typeof(PythonOps).Assembly || // IronPython.dll assembly == typeof(Microsoft.Scripting.Interpreter.LightCompiler).Assembly || // Microsoft.Scripting.dll assembly == typeof(DynamicMetaObject).Assembly) { // Microsoft.Scripting.Core.dll return true; } AssemblyName assemblyName = new AssemblyName(assembly.FullName); if (assemblyName.Name.Equals("IronPython.Modules")) { // IronPython.Modules.dll return true; } return false; } private static bool ShouldInvokeInit(PythonType cls, PythonType newObjectType, int argCnt) { // don't run __init__ if it's not a subclass of ourselves, // or if this is the user doing type(x), or if it's a standard // .NET type which doesn't have an __init__ method (this is a perf optimization) return (!cls.IsSystemType || cls.IsPythonType) && newObjectType.IsSubclassOf(cls) && (cls != TypeCache.PythonType || argCnt > 1); } // note: returns "instance" rather than type name if o is an OldInstance internal static string GetName(object o) { // Resolve Namespace-Tracker name, which would end in `namespace#` if // it is not handled indivdualy if (o is NamespaceTracker) { return ((NamespaceTracker)o).Name; } return DynamicHelpers.GetPythonType(o).Name; } // a version of GetName that also works on old-style classes internal static string GetOldName(object o) { return o is OldInstance ? GetOldName((OldInstance)o) : GetName(o); } // a version of GetName that also works on old-style classes internal static string GetOldName(OldInstance instance) { return instance._class.Name; } internal static PythonType[] ObjectTypes(object[] args) { PythonType[] types = new PythonType[args.Length]; for (int i = 0; i < args.Length; i++) { types[i] = DynamicHelpers.GetPythonType(args[i]); } return types; } internal static Type[] ConvertToTypes(PythonType[] pythonTypes) { Type[] types = new Type[pythonTypes.Length]; for (int i = 0; i < pythonTypes.Length; i++) { types[i] = ConvertToType(pythonTypes[i]); } return types; } private static Type ConvertToType(PythonType pythonType) { if (pythonType.IsNull) { return typeof(DynamicNull); } else { return pythonType.UnderlyingSystemType; } } internal static TrackerTypes GetMemberType(MemberGroup members) { TrackerTypes memberType = TrackerTypes.All; for (int i = 0; i < members.Count; i++) { MemberTracker mi = members[i]; if (mi.MemberType != memberType) { if (memberType != TrackerTypes.All) { return TrackerTypes.All; } memberType = mi.MemberType; } } return memberType; } internal static PythonTypeSlot/*!*/ GetSlot(MemberGroup group, string name, bool privateBinding) { if (group.Count == 0) { return null; } group = FilterNewSlots(group); TrackerTypes tt = GetMemberType(group); switch(tt) { case TrackerTypes.Method: bool checkStatic = false; List<MemberInfo> mems = new List<MemberInfo>(); foreach (MemberTracker mt in group) { MethodTracker metht = (MethodTracker)mt; mems.Add(metht.Method); checkStatic |= metht.IsStatic; } Type declType = group[0].DeclaringType; MemberInfo[] memArray = mems.ToArray(); FunctionType ft = GetMethodFunctionType(declType, memArray, checkStatic); return GetFinalSlotForFunction(GetBuiltinFunction(declType, group[0].Name, name, ft, memArray)); case TrackerTypes.Field: return GetReflectedField(((FieldTracker)group[0]).Field); case TrackerTypes.Property: return GetReflectedProperty((PropertyTracker)group[0], group, privateBinding); case TrackerTypes.Event: return GetReflectedEvent(((EventTracker)group[0])); case TrackerTypes.Type: TypeTracker type = (TypeTracker)group[0]; for (int i = 1; i < group.Count; i++) { type = TypeGroup.UpdateTypeEntity(type, (TypeTracker)group[i]); } if (type is TypeGroup) { return new PythonTypeUserDescriptorSlot(type, true); } return new PythonTypeUserDescriptorSlot(DynamicHelpers.GetPythonTypeFromType(type.Type), true); case TrackerTypes.Constructor: return GetConstructorFunction(group[0].DeclaringType, privateBinding); case TrackerTypes.Custom: return ((PythonCustomTracker)group[0]).GetSlot(); default: // if we have a new slot in the derived class filter out the // members from the base class. throw new InvalidOperationException(String.Format("Bad member type {0} on {1}.{2}", tt.ToString(), group[0].DeclaringType, name)); } } internal static MemberGroup FilterNewSlots(MemberGroup group) { if (GetMemberType(group) == TrackerTypes.All) { Type declType = group[0].DeclaringType; for (int i = 1; i < group.Count; i++) { if (group[i].DeclaringType != declType) { if (group[i].DeclaringType.IsSubclassOf(declType)) { declType = group[i].DeclaringType; } } } List<MemberTracker> trackers = new List<MemberTracker>(); for (int i = 0; i < group.Count; i++) { if (group[i].DeclaringType == declType) { trackers.Add(group[i]); } } if (trackers.Count != group.Count) { return new MemberGroup(trackers.ToArray()); } } return group; } private static BuiltinFunction GetConstructorFunction(Type t, bool privateBinding) { BuiltinFunction ctorFunc = InstanceOps.NonDefaultNewInst; MethodBase[] ctors = PythonTypeOps.GetConstructors(t, privateBinding, true); return GetConstructor(t, ctorFunc, ctors); } internal static MethodBase[] GetConstructors(Type t, bool privateBinding, bool includeProtected = false) { MethodBase[] ctors = CompilerHelpers.GetConstructors(t, privateBinding, includeProtected); if (t.IsEnum) { var enumCtor = typeof(PythonTypeOps).GetDeclaredMethods(nameof(CreateEnum)).Single().MakeGenericMethod(t); ctors = ctors.Concat(new[] { enumCtor }).ToArray(); } return ctors; } // support for EnumType(number) private static T CreateEnum<T>(object value) { if (value == null) { throw PythonOps.ValueError( $"None is not a valid {PythonOps.ToString(typeof(T))}" ); } try { return (T)Enum.ToObject(typeof(T), value); } catch (ArgumentException) { throw PythonOps.ValueError( $"{PythonOps.ToString(value)} is not a valid {PythonOps.ToString(typeof(T))}" ); } } internal static bool IsDefaultNew(MethodBase[] targets) { if (targets.Length == 1) { ParameterInfo[] pis = targets[0].GetParameters(); if (pis.Length == 0) { return true; } if (pis.Length == 1 && pis[0].ParameterType == typeof(CodeContext)) { return true; } } return false; } internal static BuiltinFunction GetConstructorFunction(Type type, string name) { List<MethodBase> methods = new List<MethodBase>(); bool hasDefaultConstructor = false; foreach (ConstructorInfo ci in type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { if (ci.IsPublic) { if (ci.GetParameters().Length == 0) { hasDefaultConstructor = true; } methods.Add(ci); } } if (type.IsValueType && !hasDefaultConstructor && type != typeof(void)) { try { methods.Add(typeof(ScriptingRuntimeHelpers).GetMethod("CreateInstance", ReflectionUtils.EmptyTypes).MakeGenericMethod(type)); } catch (BadImageFormatException) { // certain types (e.g. ArgIterator) won't survive the above call. // we won't let you create instances of these types. } } if (methods.Count > 0) { return BuiltinFunction.MakeFunction(name, methods.ToArray(), type); } return null; } internal static ReflectedEvent GetReflectedEvent(EventTracker tracker) { ReflectedEvent res; lock (_eventCache) { if (!_eventCache.TryGetValue(tracker, out res)) { if (PythonBinder.IsExtendedType(tracker.DeclaringType)) { _eventCache[tracker] = res = new ReflectedEvent(tracker, true); } else { _eventCache[tracker] = res = new ReflectedEvent(tracker, false); } } } return res; } internal static PythonTypeSlot/*!*/ GetFinalSlotForFunction(BuiltinFunction/*!*/ func) { if ((func.FunctionType & FunctionType.Method) != 0) { BuiltinMethodDescriptor desc; lock (_methodCache) { if (!_methodCache.TryGetValue(func, out desc)) { _methodCache[func] = desc = new BuiltinMethodDescriptor(func); } return desc; } } if (func.Targets[0].IsDefined(typeof(ClassMethodAttribute), true)) { lock (_classMethodCache) { ClassMethodDescriptor desc; if (!_classMethodCache.TryGetValue(func, out desc)) { _classMethodCache[func] = desc = new ClassMethodDescriptor(func); } return desc; } } return func; } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, null, mems); } #pragma warning disable 414 // unused fields - they're used by GetHashCode() internal struct BuiltinFunctionKey { Type DeclaringType; ReflectionCache.MethodBaseCache Cache; FunctionType FunctionType; public BuiltinFunctionKey(Type declaringType, ReflectionCache.MethodBaseCache cache, FunctionType funcType) { Cache = cache; FunctionType = funcType; DeclaringType = declaringType; } } #pragma warning restore 169 public static MethodBase[] GetNonBaseHelperMethodInfos(MemberInfo[] members) { List<MethodBase> res = new List<MethodBase>(); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb != null && !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix)) { res.Add(mb); } } return res.ToArray(); } public static MemberInfo[] GetNonBaseHelperMemberInfos(MemberInfo[] members) { List<MemberInfo> res = new List<MemberInfo>(members.Length); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb == null || !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix)) { res.Add(mi); } } return res.ToArray(); } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, name, funcType, mems); } /// <summary> /// Gets a builtin function for the given declaring type and member infos. /// /// Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction /// for each .NET method. /// /// This method takes both a cacheName and a pythonName. The cache name is the real method name. The pythonName /// is the name of the method as exposed to Python. /// </summary> internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ cacheName, string/*!*/ pythonName, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { BuiltinFunction res = null; if (mems.Length != 0) { FunctionType ft = funcType ?? GetMethodFunctionType(type, mems); type = GetBaseDeclaringType(type, mems); BuiltinFunctionKey cache = new BuiltinFunctionKey(type, new ReflectionCache.MethodBaseCache(cacheName, GetNonBaseHelperMethodInfos(mems)), ft); lock (_functions) { if (!_functions.TryGetValue(cache, out res)) { if (PythonTypeOps.GetFinalSystemType(type) == type) { IList<MethodInfo> overriddenMethods = NewTypeMaker.GetOverriddenMethods(type, cacheName); if (overriddenMethods.Count > 0) { List<MemberInfo> newMems = new List<MemberInfo>(mems); foreach (MethodInfo mi in overriddenMethods) { newMems.Add(mi); } mems = newMems.ToArray(); } } _functions[cache] = res = BuiltinFunction.MakeMethod(pythonName, ReflectionUtils.GetMethodInfos(mems), type, ft); } } } return res; } private static Type GetCommonBaseType(Type xType, Type yType) { if (xType.IsSubclassOf(yType)) { return yType; } else if (yType.IsSubclassOf(xType)) { return xType; } else if (xType == yType) { return xType; } Type xBase = xType.BaseType; Type yBase = yType.BaseType; if (xBase != null) { Type res = GetCommonBaseType(xBase, yType); if (res != null) { return res; } } if (yBase != null) { Type res = GetCommonBaseType(xType, yBase); if (res != null) { return res; } } return null; } private static Type GetBaseDeclaringType(Type type, MemberInfo/*!*/[] mems) { // get the base most declaring type, first sort the list so that // the most derived class is at the beginning. Array.Sort<MemberInfo>(mems, delegate(MemberInfo x, MemberInfo y) { if (x.DeclaringType.IsSubclassOf(y.DeclaringType)) { return -1; } else if (y.DeclaringType.IsSubclassOf(x.DeclaringType)) { return 1; } else if (x.DeclaringType == y.DeclaringType) { return 0; } // no relationship between these types, they should be base helper // methods for two different types - for example object.MemberwiseClone for // ExtensibleInt & object. We need to reset our type to the common base type. type = GetCommonBaseType(x.DeclaringType, y.DeclaringType) ?? typeof(object); // generic type definitions will have a null name. if (x.DeclaringType.FullName == null) { return -1; } else if (y.DeclaringType.FullName == null) { return 1; } return x.DeclaringType.FullName.CompareTo(y.DeclaringType.FullName); }); // then if the provided type is a subclass of the most derived type // then our declaring type is the methods declaring type. foreach (MemberInfo mb in mems) { // skip extension methods if (mb.DeclaringType.IsAssignableFrom(type)) { if (type == mb.DeclaringType || type.IsSubclassOf(mb.DeclaringType)) { type = mb.DeclaringType; break; } } } return type; } internal static ConstructorFunction GetConstructor(Type type, BuiltinFunction realTarget, params MethodBase[] mems) { ConstructorFunction res = null; if (mems.Length != 0) { ReflectionCache.MethodBaseCache cache = new ReflectionCache.MethodBaseCache("__new__", mems); lock (_ctors) { if (!_ctors.TryGetValue(cache, out res)) { _ctors[cache] = res = new ConstructorFunction(realTarget, mems); } } } return res; } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { return GetMethodFunctionType(type, methods, true); } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods, bool checkStatic) { FunctionType ft = FunctionType.None; foreach (MethodInfo mi in methods) { if (mi.IsStatic && mi.IsSpecialName) { ParameterInfo[] pis = mi.GetParameters(); if ((pis.Length == 2 && pis[0].ParameterType != typeof(CodeContext)) || (pis.Length == 3 && pis[0].ParameterType == typeof(CodeContext))) { ft |= FunctionType.BinaryOperator; if (pis[pis.Length - 2].ParameterType != type && pis[pis.Length - 1].ParameterType == type) { ft |= FunctionType.ReversedOperator; } } } if (checkStatic && IsStaticFunction(type, mi)) { ft |= FunctionType.Function; } else { ft |= FunctionType.Method; } } if (IsMethodAlwaysVisible(type, methods)) { ft |= FunctionType.AlwaysVisible; } return ft; } /// <summary> /// Checks to see if the provided members are always visible for the given type. /// /// This filters out methods such as GetHashCode and Equals on standard .NET /// types that we expose directly as Python types (e.g. object, string, etc...). /// /// It also filters out the base helper overrides that are added for supporting /// super calls on user defined types. /// </summary> private static bool IsMethodAlwaysVisible(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { bool alwaysVisible = true; if (PythonBinder.IsPythonType(type)) { // only show methods defined outside of the system types (object, string) foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType) || PythonBinder.IsExtendedType(mi.GetBaseDefinition().DeclaringType) || PythonHiddenAttribute.IsHidden(mi)) { alwaysVisible = false; break; } } } else if (typeof(IPythonObject).IsAssignableFrom(type)) { // check if this is a virtual override helper, if so we // may need to filter it out. foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType)) { alwaysVisible = false; break; } } } return alwaysVisible; } /// <summary> /// a function is static if it's a static .NET method and it's defined on the type or is an extension method /// with StaticExtensionMethod decoration. /// </summary> private static bool IsStaticFunction(Type type, MethodInfo mi) { return mi.IsStatic && // method must be truly static !mi.IsDefined(typeof(WrapperDescriptorAttribute), false) && // wrapper descriptors are instance methods (mi.DeclaringType.IsAssignableFrom(type) || mi.IsDefined(typeof(StaticExtensionMethodAttribute), false)); // or it's not an extension method or it's a static extension method } internal static PythonTypeSlot GetReflectedField(FieldInfo info) { PythonTypeSlot res; NameType nt = NameType.Field; if (!PythonBinder.IsExtendedType(info.DeclaringType) && !PythonHiddenAttribute.IsHidden(info)) { nt |= NameType.PythonField; } lock (_fieldCache) { if (!_fieldCache.TryGetValue(info, out res)) { if (nt == NameType.PythonField && info.IsLiteral) { if (info.FieldType == typeof(int)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.Int32ToObject((int)info.GetRawConstantValue()), true ); } else if (info.FieldType == typeof(bool)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.BooleanToObject((bool)info.GetRawConstantValue()), true ); } else { res = new PythonTypeUserDescriptorSlot( info.GetValue(null), true ); } } else { res = new ReflectedField(info, nt); } _fieldCache[info] = res; } } return res; } internal static string GetDocumentation(Type type) { // Python documentation var docAttr = type.GetCustomAttributes(typeof(DocumentationAttribute), false); if (docAttr != null && docAttr.Any()) { return ((DocumentationAttribute)docAttr.First()).Documentation; } if (type == typeof(DynamicNull)) return null; // Auto Doc (XML or otherwise) string autoDoc = DocBuilder.CreateAutoDoc(type); if (autoDoc == null) { autoDoc = String.Empty; } else { autoDoc += Environment.NewLine + Environment.NewLine; } // Simple generated helpbased on ctor, if available. ConstructorInfo[] cis = type.GetConstructors(); foreach (ConstructorInfo ci in cis) { autoDoc += FixCtorDoc(type, DocBuilder.CreateAutoDoc(ci, DynamicHelpers.GetPythonTypeFromType(type).Name, 0)) + Environment.NewLine; } return autoDoc; } private static string FixCtorDoc(Type type, string autoDoc) { return autoDoc.Replace("__new__(cls)", DynamicHelpers.GetPythonTypeFromType(type).Name + "()"). Replace("__new__(cls, ", DynamicHelpers.GetPythonTypeFromType(type).Name + "("); } internal static ReflectedGetterSetter GetReflectedProperty(PropertyTracker pt, MemberGroup allProperties, bool privateBinding) { ReflectedGetterSetter rp; lock (_propertyCache) { if (_propertyCache.TryGetValue(pt, out rp)) { return rp; } NameType nt = NameType.PythonProperty; MethodInfo getter = FilterProtectedGetterOrSetter(pt.GetGetMethod(true), privateBinding); MethodInfo setter = FilterProtectedGetterOrSetter(pt.GetSetMethod(true), privateBinding); if ((getter != null && PythonHiddenAttribute.IsHidden(getter, true)) || setter != null && PythonHiddenAttribute.IsHidden(setter, true)) { nt = NameType.Property; } if (!(pt is ExtensionPropertyTracker ept)) { ReflectedPropertyTracker rpt = pt as ReflectedPropertyTracker; Debug.Assert(rpt != null); if (PythonBinder.IsExtendedType(pt.DeclaringType) || PythonHiddenAttribute.IsHidden(rpt.Property, true)) { nt = NameType.Property; } if (pt.GetIndexParameters().Length == 0) { List<MethodInfo> getters = new List<MethodInfo>(); List<MethodInfo> setters = new List<MethodInfo>(); IList<ExtensionPropertyTracker> overriddenProperties = NewTypeMaker.GetOverriddenProperties((getter ?? setter).DeclaringType, pt.Name); foreach (ExtensionPropertyTracker tracker in overriddenProperties) { MethodInfo method = tracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = tracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } foreach (PropertyTracker propTracker in allProperties) { MethodInfo method = propTracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = propTracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } rp = new ReflectedProperty(rpt.Property, getters.ToArray(), setters.ToArray(), nt); } else { rp = new ReflectedIndexer(((ReflectedPropertyTracker)pt).Property, NameType.Property, privateBinding); } } else { rp = new ReflectedExtensionProperty(new ExtensionPropertyInfo(pt.DeclaringType, getter ?? setter), nt); } _propertyCache[pt] = rp; return rp; } } private static MethodInfo FilterProtectedGetterOrSetter(MethodInfo info, bool privateBinding) { if (info != null) { if (privateBinding || info.IsPublic) { return info; } if (info.IsProtected()) { return info; } } return null; } internal static bool TryInvokeUnaryOperator(CodeContext context, object o, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "UnaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable); return true; } value = null; return false; } internal static bool TryInvokeBinaryOperator(CodeContext context, object o, object arg1, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "BinaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable, arg1); return true; } value = null; return false; } internal static bool TryInvokeTernaryOperator(CodeContext context, object o, object arg1, object arg2, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "TernaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable, arg1, arg2); return true; } value = null; return false; } /// <summary> /// If we have only interfaces, we'll need to insert object's base /// </summary> internal static PythonTuple EnsureBaseType(PythonTuple bases) { bool hasInterface = false; foreach (object baseClass in bases) { if (baseClass is OldClass) continue; PythonType dt = baseClass as PythonType; if (!dt.UnderlyingSystemType.IsInterface) { return bases; } else { hasInterface = true; } } if (hasInterface || bases.Count == 0) { // We found only interfaces. We need do add System.Object to the bases return new PythonTuple(bases, TypeCache.Object); } throw PythonOps.TypeError("a new-style class can't have only classic bases"); } internal static Type GetFinalSystemType(Type type) { while (typeof(IPythonObject).IsAssignableFrom(type) && !type.IsDefined(typeof(DynamicBaseTypeAttribute), false)) { type = type.BaseType; } return type; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.BeatmapListing.Panels { public abstract class BeatmapPanel : OsuClickableContainer, IHasContextMenu { public readonly BeatmapSetInfo SetInfo; private const double hover_transition_time = 400; private const int maximum_difficulty_icons = 10; private Container content; public PreviewTrack Preview => PlayButton.Preview; public IBindable<bool> PreviewPlaying => PlayButton?.Playing; protected abstract PlayButton PlayButton { get; } protected abstract Box PreviewBar { get; } protected virtual bool FadePlayButton => true; protected override Container<Drawable> Content => content; protected Action ViewBeatmap; protected BeatmapPanel(BeatmapSetInfo setInfo) : base(HoverSampleSet.Submit) { Debug.Assert(setInfo.OnlineBeatmapSetID != null); SetInfo = setInfo; } private readonly EdgeEffectParameters edgeEffectNormal = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 1f), Radius = 2f, Colour = Color4.Black.Opacity(0.25f), }; private readonly EdgeEffectParameters edgeEffectHovered = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 5f), Radius = 10f, Colour = Color4.Black.Opacity(0.3f), }; [BackgroundDependencyLoader(permitNulls: true)] private void load(BeatmapManager beatmaps, OsuColour colours, BeatmapSetOverlay beatmapSetOverlay) { AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, EdgeEffect = edgeEffectNormal, Children = new[] { CreateBackground(), new DownloadProgressBar(SetInfo) { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Depth = -1, }, } }); Action = ViewBeatmap = () => { Debug.Assert(SetInfo.OnlineBeatmapSetID != null); beatmapSetOverlay?.FetchAndShowBeatmapSet(SetInfo.OnlineBeatmapSetID.Value); }; } protected override void Update() { base.Update(); if (PreviewPlaying.Value && Preview != null && Preview.TrackLoaded) { PreviewBar.Width = (float)(Preview.CurrentTime / Preview.Length); } } protected override bool OnHover(HoverEvent e) { content.TweenEdgeEffectTo(edgeEffectHovered, hover_transition_time, Easing.OutQuint); content.MoveToY(-4, hover_transition_time, Easing.OutQuint); if (FadePlayButton) PlayButton.FadeIn(120, Easing.InOutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { content.TweenEdgeEffectTo(edgeEffectNormal, hover_transition_time, Easing.OutQuint); content.MoveToY(0, hover_transition_time, Easing.OutQuint); if (FadePlayButton && !PreviewPlaying.Value) PlayButton.FadeOut(120, Easing.InOutQuint); base.OnHoverLost(e); } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(200, Easing.Out); PreviewPlaying.ValueChanged += playing => { PlayButton.FadeTo(playing.NewValue || IsHovered || !FadePlayButton ? 1 : 0, 120, Easing.InOutQuint); PreviewBar.FadeTo(playing.NewValue ? 1 : 0, 120, Easing.InOutQuint); }; } protected List<DifficultyIcon> GetDifficultyIcons(OsuColour colours) { var icons = new List<DifficultyIcon>(); if (SetInfo.Beatmaps.Count > maximum_difficulty_icons) { foreach (var ruleset in SetInfo.Beatmaps.Select(b => b.Ruleset).Distinct()) icons.Add(new GroupedDifficultyIcon(SetInfo.Beatmaps.FindAll(b => b.Ruleset.Equals(ruleset)), ruleset, this is ListBeatmapPanel ? Color4.White : colours.Gray5)); } else { foreach (var b in SetInfo.Beatmaps.OrderBy(beatmap => beatmap.Ruleset.ID).ThenBy(beatmap => beatmap.StarDifficulty)) icons.Add(new DifficultyIcon(b)); } return icons; } protected Drawable CreateBackground() => new UpdateableOnlineBeatmapSetCover { RelativeSizeAxes = Axes.Both, BeatmapSet = SetInfo, }; public class Statistic : FillFlowContainer { private readonly SpriteText text; private int value; public int Value { get => value; set { this.value = value; text.Text = Value.ToString(@"N0"); } } public Statistic(IconUsage icon, int value = 0) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; AutoSizeAxes = Axes.Both; Direction = FillDirection.Horizontal; Spacing = new Vector2(5f, 0f); Children = new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.SemiBold, italics: true) }, new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = icon, Shadow = true, Size = new Vector2(14), }, }; Value = value; } } public MenuItem[] ContextMenuItems => new MenuItem[] { new OsuMenuItem("View Beatmap", MenuItemType.Highlighted, ViewBeatmap), }; } }
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; namespace ZXing.PDF417.Internal.EC { /// <summary> /// <see cref="com.google.zxing.common.reedsolomon.GenericGFPoly"/> /// </summary> /// <author>Sean Owen</author> internal sealed class ModulusPoly { private readonly ModulusGF field; private readonly int[] coefficients; public ModulusPoly(ModulusGF field, int[] coefficients) { if (coefficients.Length == 0) { throw new ArgumentException(); } this.field = field; int coefficientsLength = coefficients.Length; if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" int firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { this.coefficients = new int[]{0}; } else { this.coefficients = new int[coefficientsLength - firstNonZero]; Array.Copy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.Length); } } else { this.coefficients = coefficients; } } /// <summary> /// Gets the coefficients. /// </summary> /// <value>The coefficients.</value> internal int[] Coefficients { get { return coefficients; } } /// <summary> /// degree of this polynomial /// </summary> internal int Degree { get { return coefficients.Length - 1; } } /// <summary> /// Gets a value indicating whether this instance is zero. /// </summary> /// <value>true if this polynomial is the monomial "0" /// </value> internal bool isZero { get { return coefficients[0] == 0; } } /// <summary> /// coefficient of x^degree term in this polynomial /// </summary> /// <param name="degree">The degree.</param> /// <returns>coefficient of x^degree term in this polynomial</returns> internal int getCoefficient(int degree) { return coefficients[coefficients.Length - 1 - degree]; } /// <summary> /// evaluation of this polynomial at a given point /// </summary> /// <param name="a">A.</param> /// <returns>evaluation of this polynomial at a given point</returns> internal int evaluateAt(int a) { if (a == 0) { // Just return the x^0 coefficient return getCoefficient(0); } int result = 0; if (a == 1) { // Just the sum of the coefficients foreach (var coefficient in coefficients) { result = field.add(result, coefficient); } return result; } result = coefficients[0]; int size = coefficients.Length; for (int i = 1; i < size; i++) { result = field.add(field.multiply(a, result), coefficients[i]); } return result; } /// <summary> /// Adds another Modulus /// </summary> /// <param name="other">Other.</param> internal ModulusPoly add(ModulusPoly other) { if (!field.Equals(other.field)) { throw new ArgumentException("ModulusPolys do not have same ModulusGF field"); } if (isZero) { return other; } if (other.isZero) { return this; } int[] smallerCoefficients = this.coefficients; int[] largerCoefficients = other.coefficients; if (smallerCoefficients.Length > largerCoefficients.Length) { int[] temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } int[] sumDiff = new int[largerCoefficients.Length]; int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; // Copy high-order terms only found in higher-degree polynomial's coefficients Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for (int i = lengthDiff; i < largerCoefficients.Length; i++) { sumDiff[i] = field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new ModulusPoly(field, sumDiff); } /// <summary> /// Subtract another Modulus /// </summary> /// <param name="other">Other.</param> internal ModulusPoly subtract(ModulusPoly other) { if (!field.Equals(other.field)) { throw new ArgumentException("ModulusPolys do not have same ModulusGF field"); } if (other.isZero) { return this; } return add(other.getNegative()); } /// <summary> /// Multiply by another Modulus /// </summary> /// <param name="other">Other.</param> internal ModulusPoly multiply(ModulusPoly other) { if (!field.Equals(other.field)) { throw new ArgumentException("ModulusPolys do not have same ModulusGF field"); } if (isZero || other.isZero) { return field.Zero; } int[] aCoefficients = this.coefficients; int aLength = aCoefficients.Length; int[] bCoefficients = other.coefficients; int bLength = bCoefficients.Length; int[] product = new int[aLength + bLength - 1]; for (int i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (int j = 0; j < bLength; j++) { product[i + j] = field.add(product[i + j], field.multiply(aCoeff, bCoefficients[j])); } } return new ModulusPoly(field, product); } /// <summary> /// Returns a Negative version of this instance /// </summary> internal ModulusPoly getNegative() { int size = coefficients.Length; int[] negativeCoefficients = new int[size]; for (int i = 0; i < size; i++) { negativeCoefficients[i] = field.subtract(0, coefficients[i]); } return new ModulusPoly(field, negativeCoefficients); } /// <summary> /// Multiply by a Scalar. /// </summary> /// <param name="scalar">Scalar.</param> internal ModulusPoly multiply(int scalar) { if (scalar == 0) { return field.Zero; } if (scalar == 1) { return this; } int size = coefficients.Length; int[] product = new int[size]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], scalar); } return new ModulusPoly(field, product); } /// <summary> /// Multiplies by a Monomial /// </summary> /// <returns>The by monomial.</returns> /// <param name="degree">Degree.</param> /// <param name="coefficient">Coefficient.</param> internal ModulusPoly multiplyByMonomial(int degree, int coefficient) { if (degree < 0) { throw new ArgumentException(); } if (coefficient == 0) { return field.Zero; } int size = coefficients.Length; int[] product = new int[size + degree]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], coefficient); } return new ModulusPoly(field, product); } /// <summary> /// Divide by another modulus /// </summary> /// <param name="other">Other.</param> internal ModulusPoly[] divide(ModulusPoly other) { if (!field.Equals(other.field)) { throw new ArgumentException("ModulusPolys do not have same ModulusGF field"); } if (other.isZero) { throw new DivideByZeroException(); } ModulusPoly quotient = field.Zero; ModulusPoly remainder = this; int denominatorLeadingTerm = other.getCoefficient(other.Degree); int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); while (remainder.Degree >= other.Degree && !remainder.isZero) { int degreeDifference = remainder.Degree - other.Degree; int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); ModulusPoly term = other.multiplyByMonomial(degreeDifference, scale); ModulusPoly iterationQuotient = field.buildMonomial(degreeDifference, scale); quotient = quotient.add(iterationQuotient); remainder = remainder.subtract(term); } return new ModulusPoly[] { quotient, remainder }; } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.</returns> public override String ToString() { var result = new StringBuilder(8 * Degree); for (int degree = Degree; degree >= 0; degree--) { int coefficient = getCoefficient(degree); if (coefficient != 0) { if (coefficient < 0) { result.Append(" - "); coefficient = -coefficient; } else { if (result.Length > 0) { result.Append(" + "); } } if (degree == 0 || coefficient != 1) { result.Append(coefficient); } if (degree != 0) { if (degree == 1) { result.Append('x'); } else { result.Append("x^"); result.Append(degree); } } } } return result.ToString(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Help; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Management.Automation.Tracing; using System.Net; namespace Microsoft.PowerShell.Commands { /// <summary> /// The base class of all updatable help system cmdlets (Update-Help, Save-Help) /// </summary> public class UpdatableHelpCommandBase : PSCmdlet { internal const string PathParameterSetName = "Path"; internal const string LiteralPathParameterSetName = "LiteralPath"; internal UpdatableHelpCommandType _commandType; internal UpdatableHelpSystem _helpSystem; internal bool _stopping; internal int activityId; private readonly Dictionary<string, UpdatableHelpExceptionContext> _exceptions; #region Parameters /// <summary> /// Specifies the languages to update. /// </summary> [Parameter(Position = 2)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public CultureInfo[] UICulture { get { CultureInfo[] result = null; if (_language != null) { result = new CultureInfo[_language.Length]; for (int index = 0; index < _language.Length; index++) { result[index] = new CultureInfo(_language[index]); } } return result; } set { if (value == null) return; _language = new string[value.Length]; for (int index = 0; index < value.Length; index++) { _language[index] = value[index].Name; } } } internal string[] _language; /// <summary> /// Gets or sets the credential parameter. /// </summary> [Parameter()] [Credential()] public PSCredential Credential { get { return _credential; } set { _credential = value; } } internal PSCredential _credential; /// <summary> /// Directs System.Net.WebClient whether or not to use default credentials. /// </summary> [Parameter] public SwitchParameter UseDefaultCredentials { get { return _useDefaultCredentials; } set { _useDefaultCredentials = value; } } private bool _useDefaultCredentials = false; /// <summary> /// Forces the operation to complete. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } internal bool _force; /// <summary> /// Sets the scope to which help is saved. /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public UpdateHelpScope Scope { get; set; } #endregion #region Events /// <summary> /// Handles help system progress events. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void HandleProgressChanged(object sender, UpdatableHelpProgressEventArgs e) { Debug.Assert(e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand || e.CommandType == UpdatableHelpCommandType.SaveHelpCommand); string activity = (e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand) ? HelpDisplayStrings.UpdateProgressActivityForModule : HelpDisplayStrings.SaveProgressActivityForModule; ProgressRecord progress = new ProgressRecord(activityId, StringUtil.Format(activity, e.ModuleName), e.ProgressStatus); progress.PercentComplete = e.ProgressPercent; WriteProgress(progress); } #endregion #region Constructor private static readonly Dictionary<string, string> s_metadataCache; /// <summary> /// Static constructor /// /// NOTE: FWLinks for core PowerShell modules are needed since they get loaded as snapins in a Remoting Endpoint. /// When we moved to modules in V3, we were not able to make this change as it was a risky change to make at that time. /// </summary> static UpdatableHelpCommandBase() { s_metadataCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // TODO: assign real TechNet addresses s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.PowerShell.Core", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.PowerShell.Host", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.PowerShell.Management", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.PowerShell.Security", "https://aka.ms/powershell71-help"); s_metadataCache.Add("Microsoft.WSMan.Management", "https://aka.ms/powershell71-help"); } /// <summary> /// Checks if a module is a system module, a module is a system module /// if it exists in the metadata cache. /// </summary> /// <param name="module">Module name.</param> /// <returns>True if system module, false if not.</returns> internal static bool IsSystemModule(string module) { return s_metadataCache.ContainsKey(module); } /// <summary> /// Class constructor. /// </summary> /// <param name="commandType">Command type.</param> internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType) { _commandType = commandType; _helpSystem = new UpdatableHelpSystem(this, _useDefaultCredentials); _exceptions = new Dictionary<string, UpdatableHelpExceptionContext>(); _helpSystem.OnProgressChanged += HandleProgressChanged; Random rand = new Random(); activityId = rand.Next(); } #endregion #region Implementation private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext context, Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModules, bool noErrors) { if (InitialSessionState.IsEngineModule(module.Name) && !InitialSessionState.IsNestedEngineModule(module.Name)) { WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid)); var keyTuple = new Tuple<string, Version>(module.Name, module.Version); if (!helpModules.ContainsKey(keyTuple)) { helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name])); } return; } else if (InitialSessionState.IsNestedEngineModule(module.Name)) { return; } if (string.IsNullOrEmpty(module.HelpInfoUri)) { if (!noErrors) { ProcessException(module.Name, null, new UpdatableHelpSystemException( "HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null)); } return; } if (!(module.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || module.HelpInfoUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) { if (!noErrors) { ProcessException(module.Name, null, new UpdatableHelpSystemException( "InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, module.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null)); } return; } var keyTuple2 = new Tuple<string, Version>(module.Name, module.Version); if (!helpModules.ContainsKey(keyTuple2)) { helpModules.Add(keyTuple2, new UpdatableHelpModuleInfo(module.Name, module.Guid, module.ModuleBase, module.HelpInfoUri)); } } /// <summary> /// Gets a list of modules from the given pattern. /// </summary> /// <param name="context">Execution context.</param> /// <param name="pattern">Pattern to search.</param> /// <param name="fullyQualifiedName">Module Specification.</param> /// <param name="noErrors">Do not generate errors for modules without HelpInfoUri.</param> /// <returns>A list of modules.</returns> private Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(ExecutionContext context, string pattern, ModuleSpecification fullyQualifiedName, bool noErrors) { List<PSModuleInfo> modules = null; string moduleNamePattern = null; if (pattern != null) { moduleNamePattern = pattern; modules = Utils.GetModules(pattern, context); } else if (fullyQualifiedName != null) { moduleNamePattern = fullyQualifiedName.Name; modules = Utils.GetModules(fullyQualifiedName, context); } var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>(); if (modules != null) { foreach (PSModuleInfo module in modules) { ProcessSingleModuleObject(module, context, helpModules, noErrors); } } IEnumerable<WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings( globPatterns: new[] { moduleNamePattern }, options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); foreach (KeyValuePair<string, string> name in s_metadataCache) { if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true)) { // For core snapin, there are no GUIDs. So, we need to construct the HelpInfo slightly differently if (!name.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase)) { var keyTuple = new Tuple<string, Version>(name.Key, new Version("1.0")); if (!helpModules.ContainsKey(keyTuple)) { List<PSModuleInfo> availableModules = Utils.GetModules(name.Key, context); if (availableModules != null) { foreach (PSModuleInfo module in availableModules) { keyTuple = new Tuple<string, Version>(module.Name, module.Version); if (!helpModules.ContainsKey(keyTuple)) { WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid)); helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name])); } } } } } else { var keyTuple2 = new Tuple<string, Version>(name.Key, new Version("1.0")); if (!helpModules.ContainsKey(keyTuple2)) { helpModules.Add(keyTuple2, new UpdatableHelpModuleInfo(name.Key, Guid.Empty, Utils.GetApplicationBase(context.ShellID), name.Value)); } } } } return helpModules; } /// <summary> /// Handles Ctrl+C. /// </summary> protected override void StopProcessing() { _stopping = true; _helpSystem.CancelDownload(); } /// <summary> /// End processing. /// </summary> protected override void EndProcessing() { foreach (UpdatableHelpExceptionContext exception in _exceptions.Values) { UpdatableHelpExceptionContext e = exception; if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") && ((exception.Cultures != null && exception.Cultures.Count > 1) || (exception.Modules != null && exception.Modules.Count > 1))) { // Win8: 744749 Rewriting the error message only in the case where either // multiple cultures or multiple modules are involved. e = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException( "HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern, string.Join(", ", exception.Cultures)), ErrorCategory.InvalidArgument, exception.Cultures, null)); e.Modules = exception.Modules; e.Cultures = exception.Cultures; } WriteError(e.CreateErrorRecord(_commandType)); LogContext context = MshLog.GetLogContext(Context, MyInvocation); context.Severity = "Error"; PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline, context, e.GetExceptionMessage(_commandType)); } } /// <summary> /// Main cmdlet logic for processing module names or fully qualified module names. /// </summary> /// <param name="moduleNames">Module names given by the user.</param> /// <param name="fullyQualifiedNames">FullyQualifiedNames.</param> internal void Process(IEnumerable<string> moduleNames, IEnumerable<ModuleSpecification> fullyQualifiedNames) { _helpSystem.UseDefaultCredentials = _useDefaultCredentials; if (moduleNames != null) { foreach (string name in moduleNames) { if (_stopping) { break; } ProcessModuleWithGlobbing(name); } } else if (fullyQualifiedNames != null) { foreach (var fullyQualifiedName in fullyQualifiedNames) { if (_stopping) { break; } ProcessModuleWithGlobbing(fullyQualifiedName); } } else { foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo("*", null, true)) { if (_stopping) { break; } ProcessModule(module.Value); } } } /// <summary> /// Processing module objects for Save-Help. /// </summary> /// <param name="modules">Module objects given by the user.</param> internal void Process(IEnumerable<PSModuleInfo> modules) { if (modules == null || !modules.Any()) { return; } var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>(); foreach (PSModuleInfo module in modules) { ProcessSingleModuleObject(module, Context, helpModules, false); } foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModule in helpModules) { ProcessModule(helpModule.Value); } } /// <summary> /// Processes a module with potential globbing. /// </summary> /// <param name="name">Module name with globbing.</param> private void ProcessModuleWithGlobbing(string name) { if (string.IsNullOrEmpty(name)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty)); WriteError(e.ErrorRecord); return; } foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(name, null, false)) { ProcessModule(module.Value); } } /// <summary> /// Processes a ModuleSpecification with potential globbing. /// </summary> /// <param name="fullyQualifiedName">ModuleSpecification.</param> private void ProcessModuleWithGlobbing(ModuleSpecification fullyQualifiedName) { foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(null, fullyQualifiedName, false)) { ProcessModule(module.Value); } } /// <summary> /// Processes a single module with multiple cultures. /// </summary> /// <param name="module">Module to process.</param> private void ProcessModule(UpdatableHelpModuleInfo module) { _helpSystem.CurrentModule = module.ModuleName; if (this is UpdateHelpCommand && !Directory.Exists(module.ModuleBase)) { ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("ModuleBaseMustExist", StringUtil.Format(HelpDisplayStrings.ModuleBaseMustExist), ErrorCategory.InvalidOperation, null, null)); return; } // Win8: 572882 When the system locale is English and the UI is JPN, // running "update-help" still downs English help content. var cultures = _language ?? _helpSystem.GetCurrentUICulture(); foreach (string culture in cultures) { bool installed = true; if (_stopping) { break; } try { ProcessModuleWithCulture(module, culture); } catch (IOException e) { ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("FailedToCopyFile", e.Message, ErrorCategory.InvalidOperation, null, e)); } catch (UnauthorizedAccessException e) { ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied", e.Message, ErrorCategory.PermissionDenied, null, e)); } #if !CORECLR catch (WebException e) { if (e.InnerException != null && e.InnerException is UnauthorizedAccessException) { ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied", e.InnerException.Message, ErrorCategory.PermissionDenied, null, e)); } else { ProcessException(module.ModuleName, culture, e); } } #endif catch (UpdatableHelpSystemException e) { if (e.FullyQualifiedErrorId == "HelpCultureNotSupported") { installed = false; if (_language != null) { // Display the error message only if we are not using the fallback chain ProcessException(module.ModuleName, culture, e); } } else { ProcessException(module.ModuleName, culture, e); } } catch (Exception e) { ProcessException(module.ModuleName, culture, e); } finally { if (_helpSystem.Errors.Count != 0) { foreach (Exception error in _helpSystem.Errors) { ProcessException(module.ModuleName, culture, error); } _helpSystem.Errors.Clear(); } } // If -Language is not specified, we only install // one culture from the fallback chain if (_language == null && installed) { break; } } } /// <summary> /// Process a single module with a given culture. /// </summary> /// <param name="module">Module to process.</param> /// <param name="culture">Culture to use.</param> /// <returns>True if the module has been processed, false if not.</returns> internal virtual bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture) { return false; } #endregion #region Common methods /// <summary> /// Gets a list of modules from the given pattern or ModuleSpecification. /// </summary> /// <param name="pattern">Pattern to match.</param> /// <param name="fullyQualifiedName">ModuleSpecification.</param> /// <param name="noErrors">Skip errors.</param> /// <returns>A list of modules.</returns> internal Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(string pattern, ModuleSpecification fullyQualifiedName, bool noErrors) { Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> modules = GetModuleInfo(Context, pattern, fullyQualifiedName, noErrors); if (modules.Count == 0 && _exceptions.Count == 0 && !noErrors) { var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName) : StringUtil.Format(HelpDisplayStrings.CannotMatchModulePattern, pattern); ErrorRecord errorRecord = new ErrorRecord(new Exception(errorMessage), "ModuleNotFound", ErrorCategory.InvalidArgument, pattern); WriteError(errorRecord); } return modules; } /// <summary> /// Checks if it is necessary to update help. /// </summary> /// <param name="module">ModuleInfo.</param> /// <param name="currentHelpInfo">Current HelpInfo.xml.</param> /// <param name="newHelpInfo">New HelpInfo.xml.</param> /// <param name="culture">Current culture.</param> /// <param name="force">Force update.</param> /// <returns>True if it is necessary to update help, false if not.</returns> internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo, UpdatableHelpInfo newHelpInfo, CultureInfo culture, bool force) { Debug.Assert(module != null); if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture.Name), ErrorCategory.ResourceUnavailable, null, null); } // Culture check if (!newHelpInfo.IsCultureSupported(culture)) { throw new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, culture.Name, newHelpInfo.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null); } // Version check if (!force && currentHelpInfo != null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture)) { return false; } return true; } /// <summary> /// Checks if the user has attempted to update more than once per day per module. /// </summary> /// <param name="moduleName">Module name.</param> /// <param name="path">Path to help info.</param> /// <param name="filename">Help info file name.</param> /// <param name="time">Current time (UTC).</param> /// <param name="force">If -Force is specified.</param> /// <returns>True if we are okay to update, false if not.</returns> internal bool CheckOncePerDayPerModule(string moduleName, string path, string filename, DateTime time, bool force) { // Update if -Force is specified if (force) { return true; } string helpInfoFilePath = SessionState.Path.Combine(path, filename); // No HelpInfo.xml if (!File.Exists(helpInfoFilePath)) { return true; } DateTime lastModified = File.GetLastWriteTimeUtc(helpInfoFilePath); TimeSpan difference = time - lastModified; if (difference.Days >= 1) { return true; } if (_commandType == UpdatableHelpCommandType.UpdateHelpCommand) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToUpdateHelp, moduleName)); } else if (_commandType == UpdatableHelpCommandType.SaveHelpCommand) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToSaveHelp, moduleName)); } return false; } /// <summary> /// Resolves a given path to a list of directories. /// </summary> /// <param name="path">Path to resolve.</param> /// <param name="recurse">Resolve recursively?</param> /// <param name="isLiteralPath">Treat the path / start path as a literal path?</param>/// /// <returns>A list of directories.</returns> internal IEnumerable<string> ResolvePath(string path, bool recurse, bool isLiteralPath) { List<string> resolvedPaths = new List<string>(); if (isLiteralPath) { string newPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); if (!Directory.Exists(newPath)) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, null, new ItemNotFoundException()); } resolvedPaths.Add(newPath); } else { Collection<PathInfo> resolvedPathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(path); foreach (PathInfo resolvedPath in resolvedPathInfos) { ValidatePathProvider(resolvedPath); resolvedPaths.Add(resolvedPath.ProviderPath); } } foreach (string resolvedPath in resolvedPaths) { if (recurse) { foreach (string innerResolvedPath in RecursiveResolvePathHelper(resolvedPath)) { yield return innerResolvedPath; } } else { // Win8: 566738 CmdletProviderContext context = new CmdletProviderContext(this.Context); // resolvedPath is already resolved..so no need to expand wildcards anymore context.SuppressWildcardExpansion = true; if (isLiteralPath || InvokeProvider.Item.IsContainer(resolvedPath, context)) { yield return resolvedPath; } } } yield break; } /// <summary> /// Resolves a given path to a list of directories recursively. /// </summary> /// <param name="path">Path to resolve.</param> /// <returns>A list of directories.</returns> private IEnumerable<string> RecursiveResolvePathHelper(string path) { if (System.IO.Directory.Exists(path)) { yield return path; foreach (string subDirectory in Directory.EnumerateDirectories(path)) { foreach (string subDirectory2 in RecursiveResolvePathHelper(subDirectory)) { yield return subDirectory2; } } } yield break; } #endregion #region Static methods /// <summary> /// Validates the provider of the path, only FileSystem provider is accepted. /// </summary> /// <param name="path">Path to validate.</param> internal void ValidatePathProvider(PathInfo path) { if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName) { throw new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ProviderIsNotFileSystem, path.Path)); } } #endregion #region Logging /// <summary> /// Logs a command message. /// </summary> /// <param name="message">Message to log.</param> internal void LogMessage(string message) { List<string> details = new List<string>() { message }; PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details); } #endregion #region Exception processing /// <summary> /// Processes an exception for help cmdlets. /// </summary> /// <param name="moduleName">Module name.</param> /// <param name="culture">Culture info.</param> /// <param name="e">Exception to check.</param> internal void ProcessException(string moduleName, string culture, Exception e) { UpdatableHelpSystemException except = null; if (e is UpdatableHelpSystemException) { except = (UpdatableHelpSystemException)e; } #if !CORECLR else if (e is WebException) { except = new UpdatableHelpSystemException("UnableToConnect", StringUtil.Format(HelpDisplayStrings.UnableToConnect), ErrorCategory.InvalidOperation, null, e); } #endif else if (e is PSArgumentException) { except = new UpdatableHelpSystemException("InvalidArgument", e.Message, ErrorCategory.InvalidArgument, null, e); } else { except = new UpdatableHelpSystemException("UnknownErrorId", e.Message, ErrorCategory.InvalidOperation, null, e); } if (!_exceptions.ContainsKey(except.FullyQualifiedErrorId)) { _exceptions.Add(except.FullyQualifiedErrorId, new UpdatableHelpExceptionContext(except)); } _exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName); if (culture != null) { _exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture); } } #endregion } /// <summary> /// Scope to which the help should be saved. /// </summary> public enum UpdateHelpScope { /// <summary> /// Save the help content to the user directory. CurrentUser, /// <summary> /// Save the help content to the module directory. This is the default behavior. /// </summary> AllUsers } }
//--------------------------------------------------------------------- // <copyright file="CsdlSemanticsNavigationProperty.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Microsoft.OData.Edm.Annotations; using Microsoft.OData.Edm.Csdl.Parsing.Ast; using Microsoft.OData.Edm.Library; using Microsoft.OData.Edm.Validation; namespace Microsoft.OData.Edm.Csdl.CsdlSemantics { /// <summary> /// Provides semantics for a CsdlNavigationProperty. /// </summary> internal class CsdlSemanticsNavigationProperty : CsdlSemanticsElement, IEdmNavigationProperty, IEdmCheckable { private readonly CsdlNavigationProperty navigationProperty; private readonly CsdlSemanticsEntityTypeDefinition declaringType; private readonly Cache<CsdlSemanticsNavigationProperty, IEdmTypeReference> typeCache = new Cache<CsdlSemanticsNavigationProperty, IEdmTypeReference>(); private static readonly Func<CsdlSemanticsNavigationProperty, IEdmTypeReference> ComputeTypeFunc = (me) => me.ComputeType(); private readonly Cache<CsdlSemanticsNavigationProperty, IEdmNavigationProperty> partnerCache = new Cache<CsdlSemanticsNavigationProperty, IEdmNavigationProperty>(); private static readonly Func<CsdlSemanticsNavigationProperty, IEdmNavigationProperty> ComputePartnerFunc = (me) => me.ComputePartner(); private readonly Cache<CsdlSemanticsNavigationProperty, IEdmReferentialConstraint> referentialConstraintCache = new Cache<CsdlSemanticsNavigationProperty, IEdmReferentialConstraint>(); private static readonly Func<CsdlSemanticsNavigationProperty, IEdmReferentialConstraint> ComputeReferentialConstraintFunc = (me) => me.ComputeReferentialConstraint(); private readonly Cache<CsdlSemanticsNavigationProperty, IEdmEntityType> targetEntityTypeCache = new Cache<CsdlSemanticsNavigationProperty, IEdmEntityType>(); private static readonly Func<CsdlSemanticsNavigationProperty, IEdmEntityType> ComputeTargetEntityTypeFunc = (me) => me.ComputeTargetEntityType(); private readonly Cache<CsdlSemanticsNavigationProperty, IEnumerable<EdmError>> errorsCache = new Cache<CsdlSemanticsNavigationProperty, IEnumerable<EdmError>>(); private static readonly Func<CsdlSemanticsNavigationProperty, IEnumerable<EdmError>> ComputeErrorsFunc = (me) => me.ComputeErrors(); public CsdlSemanticsNavigationProperty(CsdlSemanticsEntityTypeDefinition declaringType, CsdlNavigationProperty navigationProperty) : base(navigationProperty) { this.declaringType = declaringType; this.navigationProperty = navigationProperty; } public override CsdlSemanticsModel Model { get { return this.declaringType.Model; } } public override CsdlElement Element { get { return this.navigationProperty; } } public string Name { get { return this.navigationProperty.Name; } } public EdmOnDeleteAction OnDelete { get { return (this.navigationProperty.OnDelete != null) ? this.navigationProperty.OnDelete.Action : EdmOnDeleteAction.None; } } public IEdmStructuredType DeclaringType { get { return this.declaringType; } } public bool ContainsTarget { get { return this.navigationProperty.ContainsTarget; } } public IEdmTypeReference Type { get { return this.typeCache.GetValue(this, ComputeTypeFunc, null); } } public EdmPropertyKind PropertyKind { get { return EdmPropertyKind.Navigation; } } public IEdmNavigationProperty Partner { get { return this.partnerCache.GetValue(this, ComputePartnerFunc, cycle => null); } } public IEnumerable<EdmError> Errors { get { return this.errorsCache.GetValue(this, ComputeErrorsFunc, null); } } public IEdmReferentialConstraint ReferentialConstraint { get { return this.referentialConstraintCache.GetValue(this, ComputeReferentialConstraintFunc, null); } } private IEdmEntityType TargetEntityType { get { return this.targetEntityTypeCache.GetValue(this, ComputeTargetEntityTypeFunc, null); } } protected override IEnumerable<IEdmVocabularyAnnotation> ComputeInlineVocabularyAnnotations() { return this.Model.WrapInlineVocabularyAnnotations(this, this.declaringType.Context); } private IEdmEntityType ComputeTargetEntityType() { IEdmType target = this.Type.Definition; if (target.TypeKind == EdmTypeKind.Collection) { target = ((IEdmCollectionType)target).ElementType.Definition; } return (IEdmEntityType)target; } private IEdmNavigationProperty ComputePartner() { string partnerPropertyName = this.navigationProperty.Partner; IEdmEntityType targetEntityType = this.TargetEntityType; if (partnerPropertyName != null) { var partner = targetEntityType.FindProperty(partnerPropertyName) as IEdmNavigationProperty; if (partner == null) { partner = new UnresolvedNavigationPropertyPath(targetEntityType, partnerPropertyName, this.Location); } return partner; } foreach (IEdmNavigationProperty potentialPartner in targetEntityType.NavigationProperties()) { if (potentialPartner == this) { continue; } if (potentialPartner.Partner == this) { return potentialPartner; } } return null; } private IEdmTypeReference ComputeType() { bool wasCollection; string typeName = this.navigationProperty.Type; const string CollectionPrefix = CsdlConstants.Value_Collection + "("; if (typeName.StartsWith(CollectionPrefix, StringComparison.Ordinal) && typeName.EndsWith(")", StringComparison.Ordinal)) { wasCollection = true; typeName = typeName.Substring(CollectionPrefix.Length, (typeName.Length - CollectionPrefix.Length) - 1); } else { wasCollection = false; } IEdmEntityType targetType = this.declaringType.Context.FindType(typeName) as IEdmEntityType; if (targetType == null) { targetType = new UnresolvedEntityType(typeName, this.Location); } bool nullable = !wasCollection && (this.navigationProperty.Nullable ?? CsdlConstants.Default_Nullable); IEdmEntityTypeReference targetTypeReference = new EdmEntityTypeReference(targetType, nullable); if (wasCollection) { return new EdmCollectionTypeReference(new EdmCollectionType(targetTypeReference)); } return targetTypeReference; } private IEdmReferentialConstraint ComputeReferentialConstraint() { if (this.navigationProperty.ReferentialConstraints.Any()) { return new EdmReferentialConstraint(this.navigationProperty.ReferentialConstraints.Select(this.ComputeReferentialConstraintPropertyPair)); } return null; } private EdmReferentialConstraintPropertyPair ComputeReferentialConstraintPropertyPair(CsdlReferentialConstraint csdlConstraint) { // <EntityType Name="Product"> // ... // <Property Name="CategoryID" Type="Edm.String" Nullable="false"/> // <NavigationProperty Name="Category" Type="Self.Category" Nullable="false"> // <ReferentialConstraint Property="CategoryID" ReferencedProperty="ID" /> // </NavigationProperty> // </EntityType> // the above CategoryID is DependentProperty, ID is PrincipalProperty. IEdmStructuralProperty dependentProperty = this.declaringType.FindProperty(csdlConstraint.PropertyName) as IEdmStructuralProperty ?? new UnresolvedProperty(this.declaringType, csdlConstraint.PropertyName, csdlConstraint.Location); IEdmStructuralProperty principalProperty = this.TargetEntityType.FindProperty(csdlConstraint.ReferencedPropertyName) as IEdmStructuralProperty ?? new UnresolvedProperty(this.ToEntityType(), csdlConstraint.ReferencedPropertyName, csdlConstraint.Location); return new EdmReferentialConstraintPropertyPair(dependentProperty, principalProperty); } private IEnumerable<EdmError> ComputeErrors() { List<EdmError> errors = null; if (this.Type.IsCollection() && this.navigationProperty.Nullable.HasValue) { // TODO: this should happen at parsing time, which should remove // the code for handling type-ref based collection types and unify this parsing logic errors = AllocateAndAdd(errors, new EdmError(this.Location, EdmErrorCode.NavigationPropertyWithCollectionTypeCannotHaveNullableAttribute, Strings.CsdlParser_CannotSpecifyNullableAttributeForNavigationPropertyWithCollectionType)); } var badType = this.TargetEntityType as BadEntityType; if (badType != null) { errors = AllocateAndAdd(errors, badType.Errors); } return errors ?? Enumerable.Empty<EdmError>(); } } }
// // Manager.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Auth; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite { /// <summary>Top-level CouchbaseLite object; manages a collection of databases as a CouchDB server does. /// </summary> /// <remarks>Top-level CouchbaseLite object; manages a collection of databases as a CouchDB server does. /// </remarks> public class Manager { public const string Version = "1.0.0-beta"; public const string HttpErrorDomain = "CBLHTTP"; private static readonly ObjectWriter mapper = new ObjectWriter(); public const string DatabaseSuffixOld = ".touchdb"; public const string DatabaseSuffix = ".cblite"; public static readonly ManagerOptions DefaultOptions = new ManagerOptions(); public const string LegalCharacters = "[^a-z]{1,}[^a-z0-9_$()/+-]*$"; private ManagerOptions options; private FilePath directoryFile; private IDictionary<string, Database> databases; private IList<Replication> replications; private ScheduledExecutorService workExecutor; private HttpClientFactory defaultHttpClientFactory; [InterfaceAudience.Private] public static ObjectWriter GetObjectMapper() { return mapper; } /// <summary>Constructor</summary> /// <exception cref="System.NotSupportedException">- not currently supported</exception> [InterfaceAudience.Public] public Manager() { string detailMessage = "Parameterless constructor is not a valid API call on Android. " + " Pure java version coming soon."; throw new NotSupportedException(detailMessage); } /// <summary>Constructor</summary> /// <exception cref="System.Security.SecurityException">- Runtime exception that can be thrown by File.mkdirs() /// </exception> /// <exception cref="System.IO.IOException"></exception> [InterfaceAudience.Public] public Manager(FilePath directoryFile, ManagerOptions options) { this.directoryFile = directoryFile; this.options = (options != null) ? options : DefaultOptions; this.databases = new Dictionary<string, Database>(); this.replications = new AList<Replication>(); directoryFile.Mkdirs(); if (!directoryFile.IsDirectory()) { throw new IOException(string.Format("Unable to create directory for: %s", directoryFile )); } UpgradeOldDatabaseFiles(directoryFile); workExecutor = Executors.NewSingleThreadScheduledExecutor(); } /// <summary>Get shared instance</summary> /// <exception cref="System.NotSupportedException">- not currently supported</exception> [InterfaceAudience.Public] public static Couchbase.Lite.Manager GetSharedInstance() { string detailMessage = "getSharedInstance() is not a valid API call on Android. " + " Pure java version coming soon"; throw new NotSupportedException(detailMessage); } /// <summary>Returns YES if the given name is a valid database name.</summary> /// <remarks> /// Returns YES if the given name is a valid database name. /// (Only the characters in "abcdefghijklmnopqrstuvwxyz0123456789_$()+-/" are allowed.) /// </remarks> [InterfaceAudience.Public] public static bool IsValidDatabaseName(string databaseName) { if (databaseName.Length > 0 && databaseName.Length < 240 && ContainsOnlyLegalCharacters (databaseName) && System.Char.IsLower(databaseName[0])) { return true; } return databaseName.Equals(Replication.ReplicatorDatabaseName); } /// <summary>The root directory of this manager (as specified at initialization time.) /// </summary> [InterfaceAudience.Public] public virtual string GetDirectory() { return directoryFile.GetAbsolutePath(); } /// <summary>An array of the names of all existing databases.</summary> /// <remarks>An array of the names of all existing databases.</remarks> [InterfaceAudience.Public] public virtual IList<string> GetAllDatabaseNames() { string[] databaseFiles = directoryFile.List(new _FilenameFilter_130()); IList<string> result = new AList<string>(); foreach (string databaseFile in databaseFiles) { string trimmed = Sharpen.Runtime.Substring(databaseFile, 0, databaseFile.Length - Couchbase.Lite.Manager.DatabaseSuffix.Length); string replaced = trimmed.Replace(':', '/'); result.AddItem(replaced); } result.Sort(); return Sharpen.Collections.UnmodifiableList(result); } private sealed class _FilenameFilter_130 : FilenameFilter { public _FilenameFilter_130() { } public bool Accept(FilePath dir, string filename) { if (filename.EndsWith(Couchbase.Lite.Manager.DatabaseSuffix)) { return true; } return false; } } /// <summary>Releases all resources used by the Manager instance and closes all its databases. /// </summary> /// <remarks>Releases all resources used by the Manager instance and closes all its databases. /// </remarks> [InterfaceAudience.Public] public virtual void Close() { Log.I(Database.Tag, "Closing " + this); foreach (Database database in databases.Values) { IList<Replication> replicators = database.GetAllReplications(); if (replicators != null) { foreach (Replication replicator in replicators) { replicator.Stop(); } } database.Close(); } databases.Clear(); Log.I(Database.Tag, "Closed " + this); } /// <summary>Returns the database with the given name, or creates it if it doesn't exist. /// </summary> /// <remarks> /// Returns the database with the given name, or creates it if it doesn't exist. /// Multiple calls with the same name will return the same Database instance. /// </remarks> [InterfaceAudience.Public] public virtual Database GetDatabase(string name) { bool mustExist = false; Database db = GetDatabaseWithoutOpening(name, mustExist); if (db != null) { db.Open(); } return db; } /// <summary>Returns the database with the given name, or null if it doesn't exist.</summary> /// <remarks> /// Returns the database with the given name, or null if it doesn't exist. /// Multiple calls with the same name will return the same Database instance. /// </remarks> [InterfaceAudience.Public] public virtual Database GetExistingDatabase(string name) { bool mustExist = false; Database db = GetDatabaseWithoutOpening(name, mustExist); if (db != null) { db.Open(); } return db; } /// <summary>Replaces or installs a database from a file.</summary> /// <remarks> /// Replaces or installs a database from a file. /// This is primarily used to install a canned database on first launch of an app, in which case /// you should first check .exists to avoid replacing the database if it exists already. The /// canned database would have been copied into your app bundle at build time. /// </remarks> /// <param name="databaseName">The name of the target Database to replace or create.</param> /// <param name="databaseFile">Path of the source Database file.</param> /// <param name="attachmentsDirectory">Path of the associated Attachments directory, or null if there are no attachments. /// </param> /// <exception cref="System.IO.IOException"></exception> [InterfaceAudience.Public] public virtual void ReplaceDatabase(string databaseName, FilePath databaseFile, FilePath attachmentsDirectory) { Database database = GetDatabase(databaseName); string dstAttachmentsPath = database.GetAttachmentStorePath(); FilePath destFile = new FilePath(database.GetPath()); FileDirUtils.CopyFile(databaseFile, destFile); FilePath attachmentsFile = new FilePath(dstAttachmentsPath); FileDirUtils.DeleteRecursive(attachmentsFile); attachmentsFile.Mkdirs(); if (attachmentsDirectory != null) { FileDirUtils.CopyFolder(attachmentsDirectory, attachmentsFile); } database.ReplaceUUIDs(); } [InterfaceAudience.Public] public virtual HttpClientFactory GetDefaultHttpClientFactory() { return defaultHttpClientFactory; } [InterfaceAudience.Public] public virtual void SetDefaultHttpClientFactory(HttpClientFactory defaultHttpClientFactory ) { this.defaultHttpClientFactory = defaultHttpClientFactory; } [InterfaceAudience.Private] private static bool ContainsOnlyLegalCharacters(string databaseName) { Sharpen.Pattern p = Sharpen.Pattern.Compile("^[abcdefghijklmnopqrstuvwxyz0123456789_$()+-/]+$" ); Matcher matcher = p.Matcher(databaseName); return matcher.Matches(); } [InterfaceAudience.Private] private void UpgradeOldDatabaseFiles(FilePath directory) { FilePath[] files = directory.ListFiles(new _FilenameFilter_245()); foreach (FilePath file in files) { string oldFilename = file.GetName(); string newFilename = FilenameWithNewExtension(oldFilename, DatabaseSuffixOld, DatabaseSuffix ); FilePath newFile = new FilePath(directory, newFilename); if (newFile.Exists()) { string msg = string.Format("Cannot rename %s to %s, %s already exists", oldFilename , newFilename, newFilename); Log.W(Database.Tag, msg); continue; } bool ok = file.RenameTo(newFile); if (!ok) { string msg = string.Format("Unable to rename %s to %s", oldFilename, newFilename); throw new InvalidOperationException(msg); } } } private sealed class _FilenameFilter_245 : FilenameFilter { public _FilenameFilter_245() { } public bool Accept(FilePath file, string name) { return name.EndsWith(Couchbase.Lite.Manager.DatabaseSuffixOld); } } [InterfaceAudience.Private] private string FilenameWithNewExtension(string oldFilename, string oldExtension, string newExtension) { string oldExtensionRegex = string.Format("%s$", oldExtension); return oldFilename.ReplaceAll(oldExtensionRegex, newExtension); } [InterfaceAudience.Private] public virtual ICollection<Database> AllOpenDatabases() { return databases.Values; } /// <summary>Asynchronously dispatches a callback to run on a background thread.</summary> /// <remarks> /// Asynchronously dispatches a callback to run on a background thread. The callback will be passed /// Database instance. There is not currently a known reason to use it, it may not make /// sense on the Android API, but it was added for the purpose of having a consistent API with iOS. /// </remarks> [InterfaceAudience.Private] public virtual Future RunAsync(string databaseName, AsyncTask function) { Database database = GetDatabase(databaseName); return RunAsync(new _Runnable_290(function, database)); } private sealed class _Runnable_290 : Runnable { public _Runnable_290(AsyncTask function, Database database) { this.function = function; this.database = database; } public void Run() { function.Run(database); } private readonly AsyncTask function; private readonly Database database; } [InterfaceAudience.Private] internal virtual Future RunAsync(Runnable runnable) { return workExecutor.Submit(runnable); } [InterfaceAudience.Private] private string PathForName(string name) { if ((name == null) || (name.Length == 0) || Sharpen.Pattern.Matches(LegalCharacters , name)) { return null; } name = name.Replace('/', ':'); string result = directoryFile.GetPath() + FilePath.separator + name + Couchbase.Lite.Manager .DatabaseSuffix; return result; } [InterfaceAudience.Private] private IDictionary<string, object> ParseSourceOrTarget(IDictionary<string, object > properties, string key) { IDictionary<string, object> result = new Dictionary<string, object>(); object value = properties.Get(key); if (value is string) { result.Put("url", (string)value); } else { if (value is IDictionary) { result = (IDictionary<string, object>)value; } } return result; } [InterfaceAudience.Private] internal virtual Replication ReplicationWithDatabase(Database db, Uri remote, bool push, bool create, bool start) { foreach (Replication replicator in replications) { if (replicator.GetLocalDatabase() == db && replicator.GetRemoteUrl().Equals(remote ) && replicator.IsPull() == !push) { return replicator; } } if (!create) { return null; } Replication replicator_1 = null; bool continuous = false; if (push) { replicator_1 = new Pusher(db, remote, continuous, GetWorkExecutor()); } else { replicator_1 = new Puller(db, remote, continuous, GetWorkExecutor()); } replications.AddItem(replicator_1); if (start) { replicator_1.Start(); } return replicator_1; } [InterfaceAudience.Private] public virtual Database GetDatabaseWithoutOpening(string name, bool mustExist) { Database db = databases.Get(name); if (db == null) { if (!IsValidDatabaseName(name)) { throw new ArgumentException("Invalid database name: " + name); } if (options.IsReadOnly()) { mustExist = true; } string path = PathForName(name); if (path == null) { return null; } db = new Database(path, this); if (mustExist && !db.Exists()) { string msg = string.Format("mustExist is true and db (%s) does not exist", name); Log.W(Database.Tag, msg); return null; } db.SetName(name); databases.Put(name, db); } return db; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Private] public virtual Replication GetReplicator(IDictionary<string, object> properties) { // TODO: in the iOS equivalent of this code, there is: {@"doc_ids", _documentIDs}) - write unit test that detects this bug // TODO: ditto for "headers" Authorizer authorizer = null; Replication repl = null; Uri remote = null; IDictionary<string, object> remoteMap; IDictionary<string, object> sourceMap = ParseSourceOrTarget(properties, "source"); IDictionary<string, object> targetMap = ParseSourceOrTarget(properties, "target"); string source = (string)sourceMap.Get("url"); string target = (string)targetMap.Get("url"); bool createTargetBoolean = (bool)properties.Get("create_target"); bool createTarget = (createTargetBoolean != null && createTargetBoolean); bool continuousBoolean = (bool)properties.Get("continuous"); bool continuous = (continuousBoolean != null && continuousBoolean); bool cancelBoolean = (bool)properties.Get("cancel"); bool cancel = (cancelBoolean != null && cancelBoolean); // Map the 'source' and 'target' JSON params to a local database and remote URL: if (source == null || target == null) { throw new CouchbaseLiteException("source and target are both null", new Status(Status .BadRequest)); } bool push = false; Database db = null; string remoteStr = null; if (Couchbase.Lite.Manager.IsValidDatabaseName(source)) { db = GetExistingDatabase(source); remoteStr = target; push = true; remoteMap = targetMap; } else { remoteStr = source; if (createTarget && !cancel) { bool mustExist = false; db = GetDatabaseWithoutOpening(target, mustExist); if (!db.Open()) { throw new CouchbaseLiteException("cannot open database: " + db, new Status(Status .InternalServerError)); } } else { db = GetExistingDatabase(target); } if (db == null) { throw new CouchbaseLiteException("database is null", new Status(Status.NotFound)); } remoteMap = sourceMap; } IDictionary<string, object> authMap = (IDictionary<string, object>)remoteMap.Get( "auth"); if (authMap != null) { IDictionary<string, object> persona = (IDictionary<string, object>)authMap.Get("persona" ); if (persona != null) { string email = (string)persona.Get("email"); authorizer = new PersonaAuthorizer(email); } IDictionary<string, object> facebook = (IDictionary<string, object>)authMap.Get("facebook" ); if (facebook != null) { string email = (string)facebook.Get("email"); authorizer = new FacebookAuthorizer(email); } } try { remote = new Uri(remoteStr); } catch (UriFormatException) { throw new CouchbaseLiteException("malformed remote url: " + remoteStr, new Status (Status.BadRequest)); } if (remote == null || !remote.Scheme.StartsWith("http")) { throw new CouchbaseLiteException("remote URL is null or non-http: " + remoteStr, new Status(Status.BadRequest)); } if (!cancel) { repl = db.GetReplicator(remote, GetDefaultHttpClientFactory(), push, continuous, GetWorkExecutor()); if (repl == null) { throw new CouchbaseLiteException("unable to create replicator with remote: " + remote , new Status(Status.InternalServerError)); } if (authorizer != null) { repl.SetAuthorizer(authorizer); } string filterName = (string)properties.Get("filter"); if (filterName != null) { repl.SetFilter(filterName); IDictionary<string, object> filterParams = (IDictionary<string, object>)properties .Get("query_params"); if (filterParams != null) { repl.SetFilterParams(filterParams); } } if (push) { ((Pusher)repl).SetCreateTarget(createTarget); } } else { // Cancel replication: repl = db.GetActiveReplicator(remote, push); if (repl == null) { throw new CouchbaseLiteException("unable to lookup replicator with remote: " + remote , new Status(Status.NotFound)); } } return repl; } [InterfaceAudience.Private] public virtual ScheduledExecutorService GetWorkExecutor() { return workExecutor; } } }
// 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.Contracts; using System.Runtime.Serialization; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. [Serializable] public class ASCIIEncoding : Encoding { // Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230) [Serializable] internal sealed class ASCIIEncodingSealed : ASCIIEncoding { } // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(String chars) { // Validate input if (chars==null) throw new ArgumentNullException("chars"); Contract.EndContractBlock(); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(String chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty char arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (byteCount == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this); } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if (fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) charCount++; return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if (ch > 0x7f) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if (encoder != null) { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if (cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while (chars < charEnd) { char ch2 = *(chars++); if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement; else *(bytes++) = unchecked((byte)(ch2)); } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Initialize the buffer Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if (ch > 0x7f) { // Initialize the buffer if (fallbackBuffer == null) { if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // Are we throwing or using buffer? ThrowBytesOverflow(encoder, bytes == byteStart); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked((byte)ch); bytes++; } // Need to do encoder stuff if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if (b >= 0x80) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; char* charsForFallback; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { byte b = *(bytes++); if (b >= 0x80) // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; else *(chars++) = unchecked((char)b); } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if (b >= 0x80) { // This is an invalid byte in the ASCII encoding. if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered bool fallbackResult = fallbackBuffer.InternalFallback(byteBuffer, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // May or may not throw, but we didn't get this byte Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } *(chars) = unchecked((char)b); chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
/* * 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.Cache { using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; /// <summary> /// Cache metrics used to obtain statistics on cache. /// </summary> internal class CacheMetricsImpl : ICacheMetrics { /** */ private readonly long _cacheHits; /** */ private readonly float _cacheHitPercentage; /** */ private readonly long _cacheMisses; /** */ private readonly float _cacheMissPercentage; /** */ private readonly long _cacheGets; /** */ private readonly long _cachePuts; /** */ private readonly long _cacheRemovals; /** */ private readonly long _cacheEvictions; /** */ private readonly float _averageGetTime; /** */ private readonly float _averagePutTime; /** */ private readonly float _averageRemoveTime; /** */ private readonly float _averageTxCommitTime; /** */ private readonly float _averageTxRollbackTime; /** */ private readonly long _cacheTxCommits; /** */ private readonly long _cacheTxRollbacks; /** */ private readonly string _cacheName; /** */ private readonly long _offHeapGets; /** */ private readonly long _offHeapPuts; /** */ private readonly long _offHeapRemovals; /** */ private readonly long _offHeapEvictions; /** */ private readonly long _offHeapHits; /** */ private readonly float _offHeapHitPercentage; /** */ private readonly long _offHeapMisses; /** */ private readonly float _offHeapMissPercentage; /** */ private readonly long _offHeapEntriesCount; /** */ private readonly long _offHeapPrimaryEntriesCount; /** */ private readonly long _offHeapBackupEntriesCount; /** */ private readonly long _offHeapAllocatedSize; /** */ private readonly int _size; /** */ private readonly int _keySize; /** */ private readonly bool _isEmpty; /** */ private readonly int _dhtEvictQueueCurrentSize; /** */ private readonly int _txThreadMapSize; /** */ private readonly int _txXidMapSize; /** */ private readonly int _txCommitQueueSize; /** */ private readonly int _txPrepareQueueSize; /** */ private readonly int _txStartVersionCountsSize; /** */ private readonly int _txCommittedVersionsSize; /** */ private readonly int _txRolledbackVersionsSize; /** */ private readonly int _txDhtThreadMapSize; /** */ private readonly int _txDhtXidMapSize; /** */ private readonly int _txDhtCommitQueueSize; /** */ private readonly int _txDhtPrepareQueueSize; /** */ private readonly int _txDhtStartVersionCountsSize; /** */ private readonly int _txDhtCommittedVersionsSize; /** */ private readonly int _txDhtRolledbackVersionsSize; /** */ private readonly bool _isWriteBehindEnabled; /** */ private readonly int _writeBehindFlushSize; /** */ private readonly int _writeBehindFlushThreadCount; /** */ private readonly long _writeBehindFlushFrequency; /** */ private readonly int _writeBehindStoreBatchSize; /** */ private readonly int _writeBehindTotalCriticalOverflowCount; /** */ private readonly int _writeBehindCriticalOverflowCount; /** */ private readonly int _writeBehindErrorRetryCount; /** */ private readonly int _writeBehindBufferSize; /** */ private readonly string _keyType; /** */ private readonly string _valueType; /** */ private readonly bool _isStoreByValue; /** */ private readonly bool _isStatisticsEnabled; /** */ private readonly bool _isManagementEnabled; /** */ private readonly bool _isReadThrough; /** */ private readonly bool _isWriteThrough; /** */ private readonly bool _isValidForReading; /** */ private readonly bool _isValidForWriting; /** */ private readonly int _totalPartitionsCount; /** */ private readonly int _rebalancingPartitionsCount; /** */ private readonly long _keysToRebalanceLeft; /** */ private readonly long _rebalancingKeysRate; /** */ private readonly long _rebalancingBytesRate; /** */ private readonly long _heapEntriesCount; /** */ private readonly long _estimatedRebalancingFinishTime; /** */ private readonly long _rebalancingStartTime; /** */ private readonly long _rebalancingClearingPartitionsLeft; /// <summary> /// Initializes a new instance of the <see cref="CacheMetricsImpl"/> class. /// </summary> /// <param name="reader">The reader.</param> public CacheMetricsImpl(IBinaryRawReader reader) { _cacheHits = reader.ReadLong(); _cacheHitPercentage = reader.ReadFloat(); _cacheMisses = reader.ReadLong(); _cacheMissPercentage = reader.ReadFloat(); _cacheGets = reader.ReadLong(); _cachePuts = reader.ReadLong(); _cacheRemovals = reader.ReadLong(); _cacheEvictions = reader.ReadLong(); _averageGetTime = reader.ReadFloat(); _averagePutTime = reader.ReadFloat(); _averageRemoveTime = reader.ReadFloat(); _averageTxCommitTime = reader.ReadFloat(); _averageTxRollbackTime = reader.ReadFloat(); _cacheTxCommits = reader.ReadLong(); _cacheTxRollbacks = reader.ReadLong(); _cacheName = reader.ReadString(); _offHeapGets = reader.ReadLong(); _offHeapPuts = reader.ReadLong(); _offHeapRemovals = reader.ReadLong(); _offHeapEvictions = reader.ReadLong(); _offHeapHits = reader.ReadLong(); _offHeapHitPercentage = reader.ReadFloat(); _offHeapMisses = reader.ReadLong(); _offHeapMissPercentage = reader.ReadFloat(); _offHeapEntriesCount = reader.ReadLong(); _offHeapPrimaryEntriesCount = reader.ReadLong(); _offHeapBackupEntriesCount = reader.ReadLong(); _offHeapAllocatedSize = reader.ReadLong(); _size = reader.ReadInt(); _keySize = reader.ReadInt(); _isEmpty = reader.ReadBoolean(); _dhtEvictQueueCurrentSize = reader.ReadInt(); _txThreadMapSize = reader.ReadInt(); _txXidMapSize = reader.ReadInt(); _txCommitQueueSize = reader.ReadInt(); _txPrepareQueueSize = reader.ReadInt(); _txStartVersionCountsSize = reader.ReadInt(); _txCommittedVersionsSize = reader.ReadInt(); _txRolledbackVersionsSize = reader.ReadInt(); _txDhtThreadMapSize = reader.ReadInt(); _txDhtXidMapSize = reader.ReadInt(); _txDhtCommitQueueSize = reader.ReadInt(); _txDhtPrepareQueueSize = reader.ReadInt(); _txDhtStartVersionCountsSize = reader.ReadInt(); _txDhtCommittedVersionsSize = reader.ReadInt(); _txDhtRolledbackVersionsSize = reader.ReadInt(); _isWriteBehindEnabled = reader.ReadBoolean(); _writeBehindFlushSize = reader.ReadInt(); _writeBehindFlushThreadCount = reader.ReadInt(); _writeBehindFlushFrequency = reader.ReadLong(); _writeBehindStoreBatchSize = reader.ReadInt(); _writeBehindTotalCriticalOverflowCount = reader.ReadInt(); _writeBehindCriticalOverflowCount = reader.ReadInt(); _writeBehindErrorRetryCount = reader.ReadInt(); _writeBehindBufferSize = reader.ReadInt(); _keyType = reader.ReadString(); _valueType = reader.ReadString(); _isStoreByValue = reader.ReadBoolean(); _isStatisticsEnabled = reader.ReadBoolean(); _isManagementEnabled = reader.ReadBoolean(); _isReadThrough = reader.ReadBoolean(); _isWriteThrough = reader.ReadBoolean(); _isValidForReading = reader.ReadBoolean(); _isValidForWriting = reader.ReadBoolean(); _totalPartitionsCount = reader.ReadInt(); _rebalancingPartitionsCount = reader.ReadInt(); _keysToRebalanceLeft = reader.ReadLong(); _rebalancingKeysRate = reader.ReadLong(); _rebalancingBytesRate = reader.ReadLong(); _heapEntriesCount = reader.ReadLong(); _estimatedRebalancingFinishTime = reader.ReadLong(); _rebalancingStartTime = reader.ReadLong(); _rebalancingClearingPartitionsLeft = reader.ReadLong(); } /** <inheritDoc /> */ public long CacheHits { get { return _cacheHits; } } /** <inheritDoc /> */ public float CacheHitPercentage { get { return _cacheHitPercentage; } } /** <inheritDoc /> */ public long CacheMisses { get { return _cacheMisses; } } /** <inheritDoc /> */ public float CacheMissPercentage { get { return _cacheMissPercentage; } } /** <inheritDoc /> */ public long CacheGets { get { return _cacheGets; } } /** <inheritDoc /> */ public long CachePuts { get { return _cachePuts; } } /** <inheritDoc /> */ public long CacheRemovals { get { return _cacheRemovals; } } /** <inheritDoc /> */ public long CacheEvictions { get { return _cacheEvictions; } } /** <inheritDoc /> */ public float AverageGetTime { get { return _averageGetTime; } } /** <inheritDoc /> */ public float AveragePutTime { get { return _averagePutTime; } } /** <inheritDoc /> */ public float AverageRemoveTime { get { return _averageRemoveTime; } } /** <inheritDoc /> */ public float AverageTxCommitTime { get { return _averageTxCommitTime; } } /** <inheritDoc /> */ public float AverageTxRollbackTime { get { return _averageTxRollbackTime; } } /** <inheritDoc /> */ public long CacheTxCommits { get { return _cacheTxCommits; } } /** <inheritDoc /> */ public long CacheTxRollbacks { get { return _cacheTxRollbacks; } } /** <inheritDoc /> */ public string CacheName { get { return _cacheName; } } /** <inheritDoc /> */ public long OffHeapGets { get { return _offHeapGets; } } /** <inheritDoc /> */ public long OffHeapPuts { get { return _offHeapPuts; } } /** <inheritDoc /> */ public long OffHeapRemovals { get { return _offHeapRemovals; } } /** <inheritDoc /> */ public long OffHeapEvictions { get { return _offHeapEvictions; } } /** <inheritDoc /> */ public long OffHeapHits { get { return _offHeapHits; } } /** <inheritDoc /> */ public float OffHeapHitPercentage { get { return _offHeapHitPercentage; } } /** <inheritDoc /> */ public long OffHeapMisses { get { return _offHeapMisses; } } /** <inheritDoc /> */ public float OffHeapMissPercentage { get { return _offHeapMissPercentage; } } /** <inheritDoc /> */ public long OffHeapEntriesCount { get { return _offHeapEntriesCount; } } /** <inheritDoc /> */ public long OffHeapPrimaryEntriesCount { get { return _offHeapPrimaryEntriesCount; } } /** <inheritDoc /> */ public long OffHeapBackupEntriesCount { get { return _offHeapBackupEntriesCount; } } /** <inheritDoc /> */ public long OffHeapAllocatedSize { get { return _offHeapAllocatedSize; } } /** <inheritDoc /> */ public int Size { get { return _size; } } /** <inheritDoc /> */ public int KeySize { get { return _keySize; } } /** <inheritDoc /> */ public bool IsEmpty { get { return _isEmpty; } } /** <inheritDoc /> */ public int DhtEvictQueueCurrentSize { get { return _dhtEvictQueueCurrentSize; } } /** <inheritDoc /> */ public int TxThreadMapSize { get { return _txThreadMapSize; } } /** <inheritDoc /> */ public int TxXidMapSize { get { return _txXidMapSize; } } /** <inheritDoc /> */ public int TxCommitQueueSize { get { return _txCommitQueueSize; } } /** <inheritDoc /> */ public int TxPrepareQueueSize { get { return _txPrepareQueueSize; } } /** <inheritDoc /> */ public int TxStartVersionCountsSize { get { return _txStartVersionCountsSize; } } /** <inheritDoc /> */ public int TxCommittedVersionsSize { get { return _txCommittedVersionsSize; } } /** <inheritDoc /> */ public int TxRolledbackVersionsSize { get { return _txRolledbackVersionsSize; } } /** <inheritDoc /> */ public int TxDhtThreadMapSize { get { return _txDhtThreadMapSize; } } /** <inheritDoc /> */ public int TxDhtXidMapSize { get { return _txDhtXidMapSize; } } /** <inheritDoc /> */ public int TxDhtCommitQueueSize { get { return _txDhtCommitQueueSize; } } /** <inheritDoc /> */ public int TxDhtPrepareQueueSize { get { return _txDhtPrepareQueueSize; } } /** <inheritDoc /> */ public int TxDhtStartVersionCountsSize { get { return _txDhtStartVersionCountsSize; } } /** <inheritDoc /> */ public int TxDhtCommittedVersionsSize { get { return _txDhtCommittedVersionsSize; } } /** <inheritDoc /> */ public int TxDhtRolledbackVersionsSize { get { return _txDhtRolledbackVersionsSize; } } /** <inheritDoc /> */ public bool IsWriteBehindEnabled { get { return _isWriteBehindEnabled; } } /** <inheritDoc /> */ public int WriteBehindFlushSize { get { return _writeBehindFlushSize; } } /** <inheritDoc /> */ public int WriteBehindFlushThreadCount { get { return _writeBehindFlushThreadCount; } } /** <inheritDoc /> */ public long WriteBehindFlushFrequency { get { return _writeBehindFlushFrequency; } } /** <inheritDoc /> */ public int WriteBehindStoreBatchSize { get { return _writeBehindStoreBatchSize; } } /** <inheritDoc /> */ public int WriteBehindTotalCriticalOverflowCount { get { return _writeBehindTotalCriticalOverflowCount; } } /** <inheritDoc /> */ public int WriteBehindCriticalOverflowCount { get { return _writeBehindCriticalOverflowCount; } } /** <inheritDoc /> */ public int WriteBehindErrorRetryCount { get { return _writeBehindErrorRetryCount; } } /** <inheritDoc /> */ public int WriteBehindBufferSize { get { return _writeBehindBufferSize; } } /** <inheritDoc /> */ public string KeyType { get { return _keyType; } } /** <inheritDoc /> */ public string ValueType { get { return _valueType; } } /** <inheritDoc /> */ public bool IsStoreByValue { get { return _isStoreByValue; } } /** <inheritDoc /> */ public bool IsStatisticsEnabled { get { return _isStatisticsEnabled; } } /** <inheritDoc /> */ public bool IsManagementEnabled { get { return _isManagementEnabled; } } /** <inheritDoc /> */ public bool IsReadThrough { get { return _isReadThrough; } } /** <inheritDoc /> */ public bool IsWriteThrough { get { return _isWriteThrough; } } /** <inheritDoc /> */ public bool IsValidForReading { get { return _isValidForReading; } } /** <inheritDoc /> */ public bool IsValidForWriting { get { return _isValidForWriting; } } /** <inheritDoc /> */ public int TotalPartitionsCount { get { return _totalPartitionsCount; } } /** <inheritDoc /> */ public int RebalancingPartitionsCount { get { return _rebalancingPartitionsCount; } } /** <inheritDoc /> */ public long KeysToRebalanceLeft { get { return _keysToRebalanceLeft; } } /** <inheritDoc /> */ public long RebalancingKeysRate { get { return _rebalancingKeysRate; } } /** <inheritDoc /> */ public long RebalancingBytesRate { get { return _rebalancingBytesRate; } } /** <inheritDoc /> */ public long HeapEntriesCount { get { return _heapEntriesCount; } } /** <inheritDoc /> */ public long EstimatedRebalancingFinishTime { get { return _estimatedRebalancingFinishTime; } } /** <inheritDoc /> */ public long RebalancingStartTime { get { return _rebalancingStartTime; } } /** <inheritDoc /> */ public long RebalanceClearingPartitionsLeft { get { return _rebalancingClearingPartitionsLeft; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.VisualTree; namespace Avalonia.Controls.Presenters { /// <summary> /// Presents a single item of data inside a <see cref="TemplatedControl"/> template. /// </summary> public class ContentPresenter : Control, IContentPresenter { /// <summary> /// Defines the <see cref="Background"/> property. /// </summary> public static readonly StyledProperty<IBrush> BackgroundProperty = Border.BackgroundProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> public static readonly AvaloniaProperty<IBrush> BorderBrushProperty = Border.BorderBrushProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderThickness"/> property. /// </summary> public static readonly StyledProperty<double> BorderThicknessProperty = Border.BorderThicknessProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Child"/> property. /// </summary> public static readonly DirectProperty<ContentPresenter, IControl> ChildProperty = AvaloniaProperty.RegisterDirect<ContentPresenter, IControl>( nameof(Child), o => o.Child); /// <summary> /// Defines the <see cref="Content"/> property. /// </summary> public static readonly StyledProperty<object> ContentProperty = ContentControl.ContentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="ContentTemplate"/> property. /// </summary> public static readonly StyledProperty<IDataTemplate> ContentTemplateProperty = ContentControl.ContentTemplateProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="CornerRadius"/> property. /// </summary> public static readonly StyledProperty<float> CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="HorizontalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty = ContentControl.HorizontalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="VerticalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty = ContentControl.VerticalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Padding"/> property. /// </summary> public static readonly StyledProperty<Thickness> PaddingProperty = Border.PaddingProperty.AddOwner<ContentPresenter>(); private IControl _child; private bool _createdChild; private IDataTemplate _dataTemplate; /// <summary> /// Initializes static members of the <see cref="ContentPresenter"/> class. /// </summary> static ContentPresenter() { ContentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged); ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged); TemplatedParentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.TemplatedParentChanged); } /// <summary> /// Initializes a new instance of the <see cref="ContentPresenter"/> class. /// </summary> public ContentPresenter() { } /// <summary> /// Gets or sets a brush with which to paint the background. /// </summary> public IBrush Background { get { return GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// Gets or sets a brush with which to paint the border. /// </summary> public IBrush BorderBrush { get { return GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// Gets or sets the thickness of the border. /// </summary> public double BorderThickness { get { return GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// Gets the control displayed by the presenter. /// </summary> public IControl Child { get { return _child; } private set { SetAndRaise(ChildProperty, ref _child, value); } } /// <summary> /// Gets or sets the content to be displayed by the presenter. /// </summary> public object Content { get { return GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// Gets or sets the data template used to display the content of the control. /// </summary> public IDataTemplate ContentTemplate { get { return GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); } } /// <summary> /// Gets or sets the radius of the border rounded corners. /// </summary> public float CornerRadius { get { return GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } /// <summary> /// Gets or sets the horizontal alignment of the content within the control. /// </summary> public HorizontalAlignment HorizontalContentAlignment { get { return GetValue(HorizontalContentAlignmentProperty); } set { SetValue(HorizontalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the vertical alignment of the content within the control. /// </summary> public VerticalAlignment VerticalContentAlignment { get { return GetValue(VerticalContentAlignmentProperty); } set { SetValue(VerticalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the padding to place around the <see cref="Child"/> control. /// </summary> public Thickness Padding { get { return GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <inheritdoc/> public override sealed void ApplyTemplate() { if (!_createdChild && ((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } } /// <inheritdoc/> protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); _dataTemplate = null; } /// <summary> /// Updates the <see cref="Child"/> control based on the control's <see cref="Content"/>. /// </summary> /// <remarks> /// Usually the <see cref="Child"/> control is created automatically when /// <see cref="ApplyTemplate"/> is called; however for this to happen, the control needs to /// be attached to a logical tree (if the control is not attached to the logical tree, it /// is reasonable to expect that the DataTemplates needed for the child are not yet /// available). This method forces the <see cref="Child"/> control's creation at any point, /// and is particularly useful in unit tests. /// </remarks> public void UpdateChild() { var content = Content; var oldChild = Child; var newChild = CreateChild(); // Remove the old child if we're not recycling it. if (oldChild != null && newChild != oldChild) { VisualChildren.Remove(oldChild); } // Set the DataContext if the data isn't a control. if (!(content is IControl)) { DataContext = content; } else { ClearValue(DataContextProperty); } // Update the Child. if (newChild == null) { Child = null; } else if (newChild != oldChild) { ((ISetInheritanceParent)newChild).SetParent(this); Child = newChild; if (oldChild?.Parent == this) { LogicalChildren.Remove(oldChild); } if (newChild.Parent == null) { var templatedLogicalParent = TemplatedParent as ILogical; if (templatedLogicalParent != null) { ((ISetLogicalParent)newChild).SetParent(templatedLogicalParent); } else { LogicalChildren.Add(newChild); } } VisualChildren.Add(newChild); } _createdChild = true; } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); _createdChild = false; InvalidateMeasure(); } /// <inheritdoc/> public override void Render(DrawingContext context) { var background = Background; var borderBrush = BorderBrush; var borderThickness = BorderThickness; var cornerRadius = CornerRadius; var rect = new Rect(Bounds.Size).Deflate(BorderThickness); if (background != null) { context.FillRectangle(background, rect, cornerRadius); } if (borderBrush != null && borderThickness > 0) { context.DrawRectangle(new Pen(borderBrush, borderThickness), rect, cornerRadius); } } /// <summary> /// Creates the child control. /// </summary> /// <returns>The child control or null.</returns> protected virtual IControl CreateChild() { var content = Content; var oldChild = Child; var newChild = content as IControl; if (content != null && newChild == null) { var dataTemplate = this.FindDataTemplate(content, ContentTemplate) ?? FuncDataTemplate.Default; // We have content and it isn't a control, so if the new data template is the same // as the old data template, try to recycle the existing child control to display // the new data. if (dataTemplate == _dataTemplate && dataTemplate.SupportsRecycling) { newChild = oldChild; } else { _dataTemplate = dataTemplate; newChild = _dataTemplate.Build(content); // Give the new control its own name scope. if (newChild is Control controlResult) { NameScope.SetNameScope(controlResult, new NameScope()); } } } else { _dataTemplate = null; } return newChild; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { var child = Child; var padding = Padding + new Thickness(BorderThickness); if (child != null) { child.Measure(availableSize.Deflate(padding)); return child.DesiredSize.Inflate(padding); } else { return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top); } } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var child = Child; if (child != null) { var padding = Padding + new Thickness(BorderThickness); var sizeMinusPadding = finalSize.Deflate(padding); var size = sizeMinusPadding; var horizontalAlignment = HorizontalContentAlignment; var verticalAlignment = VerticalContentAlignment; var originX = padding.Left; var originY = padding.Top; if (horizontalAlignment != HorizontalAlignment.Stretch) { size = size.WithWidth(child.DesiredSize.Width); } if (verticalAlignment != VerticalAlignment.Stretch) { size = size.WithHeight(child.DesiredSize.Height); } switch (horizontalAlignment) { case HorizontalAlignment.Stretch: case HorizontalAlignment.Center: originX += (sizeMinusPadding.Width - size.Width) / 2; break; case HorizontalAlignment.Right: originX = size.Width - child.DesiredSize.Width; break; } switch (verticalAlignment) { case VerticalAlignment.Stretch: case VerticalAlignment.Center: originY += (sizeMinusPadding.Height - size.Height) / 2; break; case VerticalAlignment.Bottom: originY = size.Height - child.DesiredSize.Height; break; } child.Arrange(new Rect(originX, originY, size.Width, size.Height)); } return finalSize; } /// <summary> /// Called when the <see cref="Content"/> property changes. /// </summary> /// <param name="e">The event args.</param> private void ContentChanged(AvaloniaPropertyChangedEventArgs e) { _createdChild = false; if (((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } else if (Child != null) { VisualChildren.Remove(Child); LogicalChildren.Remove(Child); Child = null; _dataTemplate = null; } InvalidateMeasure(); } private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e) { (e.NewValue as IContentPresenterHost)?.RegisterContentPresenter(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace System.Data.Common { internal sealed class DBConnectionString { // instances of this class are intended to be immutable, i.e readonly // used by permission classes so it is much easier to verify correctness // when not worried about the class being modified during execution private static class KEY { internal const string Password = "password"; internal const string PersistSecurityInfo = "persist security info"; internal const string Pwd = "pwd"; }; // this class is serializable with Everett, so ugly field names can't be changed private readonly string _encryptedUsersConnectionString; // hash of unique keys to values private readonly Dictionary<string, string> _parsetable; // a linked list of key/value and their length in _encryptedUsersConnectionString private readonly NameValuePair _keychain; // track the existance of "password" or "pwd" in the connection string // not used for anything anymore but must keep it set correct for V1.1 serialization private readonly bool _hasPassword; private readonly string[] _restrictionValues; private readonly string _restrictions; private readonly KeyRestrictionBehavior _behavior; #pragma warning disable 169 // this field is no longer used, hence the warning was disabled // however, it can not be removed or it will break serialization with V1.1 private readonly string _encryptedActualConnectionString; #pragma warning restore 169 internal DBConnectionString(string value, string restrictions, KeyRestrictionBehavior behavior, Dictionary<string, string> synonyms, bool useOdbcRules) : this(new DbConnectionOptions(value, synonyms, useOdbcRules), restrictions, behavior, synonyms, false) { // useOdbcRules is only used to parse the connection string, not to parse restrictions because values don't apply there // the hashtable doesn't need clone since it isn't shared with anything else } internal DBConnectionString(DbConnectionOptions connectionOptions) : this(connectionOptions, (string)null, KeyRestrictionBehavior.AllowOnly, null, true) { // used by DBDataPermission to convert from DbConnectionOptions to DBConnectionString // since backward compatability requires Everett level classes } private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Dictionary<string, string> synonyms, bool mustCloneDictionary) { // used by DBDataPermission Debug.Assert(null != connectionOptions, "null connectionOptions"); switch (behavior) { case KeyRestrictionBehavior.PreventUsage: case KeyRestrictionBehavior.AllowOnly: _behavior = behavior; break; default: throw ADP.InvalidKeyRestrictionBehavior(behavior); } // grab all the parsed details from DbConnectionOptions _encryptedUsersConnectionString = connectionOptions.UsersConnectionString(false); _hasPassword = connectionOptions._hasPasswordKeyword; _parsetable = connectionOptions.Parsetable; _keychain = connectionOptions._keyChain; // we do not want to serialize out user password unless directed so by "persist security info=true" // otherwise all instances of user's password will be replaced with "*" if (_hasPassword && !connectionOptions.HasPersistablePassword) { if (mustCloneDictionary) { // clone the hashtable to replace user's password/pwd value with "*" // we only need to clone if coming from DbConnectionOptions and password exists _parsetable = new Dictionary<string, string>(_parsetable); } // different than Everett in that instead of removing password/pwd from // the hashtable, we replace the value with '*'. This is okay since we // serialize out with '*' so already knows what we do. Better this way // than to treat password specially later on which causes problems. const string star = "*"; if (_parsetable.ContainsKey(KEY.Password)) { _parsetable[KEY.Password] = star; } if (_parsetable.ContainsKey(KEY.Pwd)) { _parsetable[KEY.Pwd] = star; } // replace user's password/pwd value with "*" in the linked list and build a new string _keychain = connectionOptions.ReplacePasswordPwd(out _encryptedUsersConnectionString, true); } if (!string.IsNullOrEmpty(restrictions)) { _restrictionValues = ParseRestrictions(restrictions, synonyms); _restrictions = restrictions; } } private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior) { // used by intersect for two equal connection strings with different restrictions _encryptedUsersConnectionString = connectionString._encryptedUsersConnectionString; _parsetable = connectionString._parsetable; _keychain = connectionString._keychain; _hasPassword = connectionString._hasPassword; _restrictionValues = restrictionValues; _restrictions = null; _behavior = behavior; Verify(restrictionValues); } internal KeyRestrictionBehavior Behavior { get { return _behavior; } } internal string ConnectionString { get { return _encryptedUsersConnectionString; } } internal bool IsEmpty { get { return (null == _keychain); } } internal NameValuePair KeyChain { get { return _keychain; } } internal string Restrictions { get { string restrictions = _restrictions; if (null == restrictions) { string[] restrictionValues = _restrictionValues; if ((null != restrictionValues) && (0 < restrictionValues.Length)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < restrictionValues.Length; ++i) { if (!string.IsNullOrEmpty(restrictionValues[i])) { builder.Append(restrictionValues[i]); builder.Append("=;"); } #if DEBUG else { Debug.Fail("empty restriction"); } #endif } restrictions = builder.ToString(); } } return ((null != restrictions) ? restrictions : ""); } } internal string this[string keyword] { get { return (string)_parsetable[keyword]; } } internal bool ContainsKey(string keyword) { return _parsetable.ContainsKey(keyword); } internal DBConnectionString Intersect(DBConnectionString entry) { KeyRestrictionBehavior behavior = _behavior; string[] restrictionValues = null; if (null == entry) { //Debug.WriteLine("0 entry AllowNothing"); behavior = KeyRestrictionBehavior.AllowOnly; } else if (_behavior != entry._behavior) { // subset of the AllowOnly array behavior = KeyRestrictionBehavior.AllowOnly; if (KeyRestrictionBehavior.AllowOnly == entry._behavior) { // this PreventUsage and entry AllowOnly if (!ADP.IsEmptyArray(_restrictionValues)) { if (!ADP.IsEmptyArray(entry._restrictionValues)) { //Debug.WriteLine("1 this PreventUsage with restrictions and entry AllowOnly with restrictions"); restrictionValues = NewRestrictionAllowOnly(entry._restrictionValues, _restrictionValues); } else { //Debug.WriteLine("2 this PreventUsage with restrictions and entry AllowOnly with no restrictions"); } } else { //Debug.WriteLine("3/4 this PreventUsage with no restrictions and entry AllowOnly"); restrictionValues = entry._restrictionValues; } } else if (!ADP.IsEmptyArray(_restrictionValues)) { // this AllowOnly and entry PreventUsage if (!ADP.IsEmptyArray(entry._restrictionValues)) { //Debug.WriteLine("5 this AllowOnly with restrictions and entry PreventUsage with restrictions"); restrictionValues = NewRestrictionAllowOnly(_restrictionValues, entry._restrictionValues); } else { //Debug.WriteLine("6 this AllowOnly and entry PreventUsage with no restrictions"); restrictionValues = _restrictionValues; } } else { //Debug.WriteLine("7/8 this AllowOnly with no restrictions and entry PreventUsage"); } } else if (KeyRestrictionBehavior.PreventUsage == _behavior) { // both PreventUsage if (ADP.IsEmptyArray(_restrictionValues)) { //Debug.WriteLine("9/10 both PreventUsage and this with no restrictions"); restrictionValues = entry._restrictionValues; } else if (ADP.IsEmptyArray(entry._restrictionValues)) { //Debug.WriteLine("11 both PreventUsage and entry with no restrictions"); restrictionValues = _restrictionValues; } else { //Debug.WriteLine("12 both PreventUsage with restrictions"); restrictionValues = NoDuplicateUnion(_restrictionValues, entry._restrictionValues); } } else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues)) { // both AllowOnly with restrictions if (_restrictionValues.Length <= entry._restrictionValues.Length) { //Debug.WriteLine("13a this AllowOnly with restrictions and entry AllowOnly with restrictions"); restrictionValues = NewRestrictionIntersect(_restrictionValues, entry._restrictionValues); } else { //Debug.WriteLine("13b this AllowOnly with restrictions and entry AllowOnly with restrictions"); restrictionValues = NewRestrictionIntersect(entry._restrictionValues, _restrictionValues); } } else { // both AllowOnly //Debug.WriteLine("14/15/16 this AllowOnly and entry AllowOnly but no restrictions"); } // verify _hasPassword & _parsetable are in [....] between Everett/Whidbey Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this"); Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior); ValidateCombinedSet(this, value); ValidateCombinedSet(entry, value); return value; } [Conditional("DEBUG")] private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet) { Debug.Assert(combinedSet != null, "The combined connection string should not be null"); if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null)) { if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly) { if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly) { // Component==Allow, Combined==Allow // All values in the Combined Set should also be in the Component Set // Combined - Component == null Debug.Assert(combinedSet._restrictionValues.Except(componentSet._restrictionValues).Count() == 0, "Combined set allows values not allowed by component set"); } else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) { // Component==Allow, Combined==PreventUsage // Preventions override allows, so there is nothing to check here } else { Debug.Fail($"Unknown behavior for combined set: {combinedSet._behavior}"); } } else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage) { if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly) { // Component==PreventUsage, Combined==Allow // There shouldn't be any of the values from the Component Set in the Combined Set // Intersect(Component, Combined) == null Debug.Assert(combinedSet._restrictionValues.Intersect(componentSet._restrictionValues).Count() == 0, "Combined values allows values prevented by component set"); } else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) { // Component==PreventUsage, Combined==PreventUsage // All values in the Component Set should also be in the Combined Set // Component - Combined == null Debug.Assert(componentSet._restrictionValues.Except(combinedSet._restrictionValues).Count() == 0, "Combined values does not prevent all of the values prevented by the component set"); } else { Debug.Fail($"Unknown behavior for combined set: {combinedSet._behavior}"); } } else { Debug.Fail($"Unknown behavior for component set: {componentSet._behavior}"); } } } private bool IsRestrictedKeyword(string key) { // restricted if not found return ((null == _restrictionValues) || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal))); } internal bool IsSupersetOf(DBConnectionString entry) { Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this"); Debug.Assert(!entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); switch (_behavior) { case KeyRestrictionBehavior.AllowOnly: // every key must either be in the resticted connection string or in the allowed keywords // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys for (NameValuePair current = entry.KeyChain; null != current; current = current.Next) { if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name)) { return false; } } break; case KeyRestrictionBehavior.PreventUsage: // every key can not be in the restricted keywords (even if in the restricted connection string) if (null != _restrictionValues) { foreach (string restriction in _restrictionValues) { if (entry.ContainsKey(restriction)) { return false; } } } break; default: Debug.Fail("invalid KeyRestrictionBehavior"); throw ADP.InvalidKeyRestrictionBehavior(_behavior); } return true; } private static string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage) { List<string> newlist = null; for (int i = 0; i < allowonly.Length; ++i) { if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal)) { if (null == newlist) { newlist = new List<string>(); } newlist.Add(allowonly[i]); } } string[] restrictionValues = null; if (null != newlist) { restrictionValues = newlist.ToArray(); } Verify(restrictionValues); return restrictionValues; } private static string[] NewRestrictionIntersect(string[] a, string[] b) { List<string> newlist = null; for (int i = 0; i < a.Length; ++i) { if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal)) { if (null == newlist) { newlist = new List<string>(); } newlist.Add(a[i]); } } string[] restrictionValues = null; if (newlist != null) { restrictionValues = newlist.ToArray(); } Verify(restrictionValues); return restrictionValues; } private static string[] NoDuplicateUnion(string[] a, string[] b) { #if DEBUG Debug.Assert(null != a && 0 < a.Length, "empty a"); Debug.Assert(null != b && 0 < b.Length, "empty b"); Verify(a); Verify(b); #endif List<string> newlist = new List<string>(a.Length + b.Length); for (int i = 0; i < a.Length; ++i) { newlist.Add(a[i]); } for (int i = 0; i < b.Length; ++i) { // find duplicates if (0 > Array.BinarySearch(a, b[i], StringComparer.Ordinal)) { newlist.Add(b[i]); } } string[] restrictionValues = newlist.ToArray(); Array.Sort(restrictionValues, StringComparer.Ordinal); Verify(restrictionValues); return restrictionValues; } private static string[] ParseRestrictions(string restrictions, Dictionary<string, string> synonyms) { List<string> restrictionValues = new List<string>(); StringBuilder buffer = new StringBuilder(restrictions.Length); int nextStartPosition = 0; int endPosition = restrictions.Length; while (nextStartPosition < endPosition) { int startPosition = nextStartPosition; string keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue); if (!string.IsNullOrEmpty(keyname)) { string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (string.IsNullOrEmpty(realkeyname)) { throw ADP.KeywordNotSupported(keyname); } restrictionValues.Add(realkeyname); } } return RemoveDuplicates(restrictionValues.ToArray()); } internal static string[] RemoveDuplicates(string[] restrictions) { int count = restrictions.Length; if (0 < count) { Array.Sort(restrictions, StringComparer.Ordinal); for (int i = 1; i < restrictions.Length; ++i) { string prev = restrictions[i - 1]; if ((0 == prev.Length) || (prev == restrictions[i])) { restrictions[i - 1] = null; count--; } } if (0 == restrictions[restrictions.Length - 1].Length) { restrictions[restrictions.Length - 1] = null; count--; } if (count != restrictions.Length) { string[] tmp = new string[count]; count = 0; for (int i = 0; i < restrictions.Length; ++i) { if (null != restrictions[i]) { tmp[count++] = restrictions[i]; } } restrictions = tmp; } } Verify(restrictions); return restrictions; } [ConditionalAttribute("DEBUG")] private static void Verify(string[] restrictionValues) { if (null != restrictionValues) { for (int i = 1; i < restrictionValues.Length; ++i) { Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i - 1]), "empty restriction"); Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i]), "empty restriction"); Debug.Assert(0 >= StringComparer.Ordinal.Compare(restrictionValues[i - 1], restrictionValues[i])); } } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; //using EFDAL = GatewayBusinessEntities;\ //using GatewayContext = IoerContentBusinessEntities; using EFDAL = IoerContentBusinessEntities; using ILPathways.Business; using ILPathways.Common; using ILPathways.DAL; using Patron = LRWarehouse.Business.Patron; namespace Isle.BizServices { public class GroupServices : ServiceHelper { string thisClassName = "GroupServices"; EFDAL.GatewayContext ctx = new EFDAL.GatewayContext(); #region Group Management Constants /// <summary> /// Session variable for group-user search parameters /// </summary> public static string GROUPS_SESSIONVAR_USERSEARCH_PARMS = "group_user_search_parms"; public static string CONTROLLER_CURRENT_GROUP = "CurrentGroup"; public static int CONTROLLER_PANE_SEARCH = 0; public static int CONTROLLER_PANE_DETAIL = 1; public static int CONTROLLER_PANE_TEAM = 2; public static int CONTROLLER_PANE_CUSTOMERS = 2; public static int CONTROLLER_PANE_PRIVILEGES = 3; public static int CONTROLLER_PANE_CUSTOMER_DETAIL = 4; public static string AUTHORIZATION_GROUP_TYPE = "Authorization"; public static string PERSONAL_GROUP_TYPE = "PersonalGroup"; #endregion #region properties string _instanceGroupCode = CONTROLLER_CURRENT_GROUP; /// <summary> /// Contains code to use for session key for current group instance - set on load by child controls /// </summary> public string InstanceGroupCode { get { return _instanceGroupCode; } set { _instanceGroupCode = value; } } /// <summary> /// INTERNAL PROPERTY: CurrentRecord /// Set initially and store in Session /// WARNING - have to be careful if user can open more than one group - future may be just append id to code or even use rowId! /// </summary> public AppGroup CurrentGroup { get { try { if ( HttpContext.Current.Session[ "CurrentGroup" ] == null ) HttpContext.Current.Session[ "CurrentGroup" ] = new AppGroup(); return HttpContext.Current.Session[ "CurrentGroup" ] as AppGroup; } catch { HttpContext.Current.Session[ "CurrentGroup" ] = new AppGroup(); return HttpContext.Current.Session[ "CurrentGroup" ] as AppGroup; } } set { HttpContext.Current.Session[ "CurrentGroup" ] = value; } } /// <summary> /// Store retrieve whether the parent record just changed /// </summary> public bool DidParentRecordChange { get { try { if ( HttpContext.Current.Session[ "CurrentGroup_DidParentIdChange" ] == null ) HttpContext.Current.Session[ "CurrentGroup_DidParentIdChange" ] = false; return bool.Parse( HttpContext.Current.Session[ "CurrentGroup_DidParentIdChange" ].ToString() ); } catch { HttpContext.Current.Session[ "CurrentGroup_DidParentIdChange" ] = false; return false; } } set { HttpContext.Current.Session[ "CurrentGroup_DidParentIdChange" ] = value; } } /// <summary> /// Get/Set Last selected user from the group member pane /// </summary> public int LastSelectedGroupMemberId { get { try { if ( HttpContext.Current.Session[ "CurrentGroup_GroupMemberId" ] == null ) HttpContext.Current.Session[ "CurrentGroup_GroupMemberId" ] = 0; return Int32.Parse( HttpContext.Current.Session[ "CurrentGroup_GroupMemberId" ].ToString() ); } catch { HttpContext.Current.Session[ "CurrentGroup_GroupMemberId" ] = 0; return 0; } } set { HttpContext.Current.Session[ "CurrentGroup_GroupMemberId" ] = value.ToString(); } } /// <summary> /// Get/Set Last selected user from the group team member pane /// </summary> public int LastSelectedGroupTeamMemberId { get { try { if ( HttpContext.Current.Session[ "CurrentGroup_GroupTeamMemberId" ] == null ) HttpContext.Current.Session[ "CurrentGroup_GroupTeamMemberId" ] = 0; return Int32.Parse( HttpContext.Current.Session[ "CurrentGroup_GroupTeamMemberId" ].ToString() ); } catch { HttpContext.Current.Session[ "CurrentGroup_GroupTeamMemberId" ] = 0; return 0; } } set { HttpContext.Current.Session[ "CurrentGroup_GroupTeamMemberId" ] = value.ToString(); } } /// <summary> /// Store retrieve the last containter (ex accordion pane, or a tab index) /// </summary> public int LastActiveContainerIdx { get { try { if ( HttpContext.Current.Session[ "CurrentGroup_ViewIndx" ] == null ) HttpContext.Current.Session[ "CurrentGroup_ViewIndx" ] = 0; return Int32.Parse( HttpContext.Current.Session[ "CurrentGroup_ViewIndx" ].ToString() ); } catch { HttpContext.Current.Session[ "CurrentGroup_ViewIndx" ] = 0; return 0; } } set { HttpContext.Current.Session[ "CurrentGroup_ViewIndx" ] = value.ToString(); } } /// <summary> /// Store retrieve the last active pane index /// </summary> public int LastActiveContainer { get { try { if ( HttpContext.Current.Session[ "CurrentGroup_LastAccordianPane" ] == null ) HttpContext.Current.Session[ "CurrentGroup_LastAccordianPane" ] = 0; return Int32.Parse( HttpContext.Current.Session[ "CurrentGroup_LastAccordianPane" ].ToString() ); } catch { return -1; } } set { HttpContext.Current.Session[ "CurrentGroup_LastAccordianPane" ] = value.ToString(); } } #endregion #region General group managment stuff /// <summary> /// struct for transporting user search parameters between a group and a search control /// - Should instantiate with the new operator to endure all properties are initialized /// </summary> [Serializable] public struct GroupUserSearchParameters { public string searchTitle; public string groupId; public string roleId; public string childEntityType; public string searchLwia; public bool isSYEPSearch; public bool isSYEP_ReturningSearch; public bool isElevateAmericaSearch; public bool showCloseButton; public string emailNoticeCode; public string programCode; } #endregion #region Groups public static bool Delete( int id, ref string statusMessage ) { return GroupManager.Delete( id, ref statusMessage ); }// public static int Create( AppGroup entity, ref string statusMessage ) { return GroupManager.Create( entity, ref statusMessage); } public static string Update( AppGroup entity ) { return GroupManager.Update( entity ); } public static AppGroup Get( int id) { return GroupManager.Get( id ); }// public static AppGroup GetByCode( string groupCode ) { return GroupManager.GetByCode( groupCode ); }// public static DataSet Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows ) { return GroupManager.Search( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows ); } #endregion #region Current Groups methods - use specific codes as can be multiple group related pages active in same session /// <summary> /// Check if a group of requrest type has been saved in session /// </summary> /// <returns>True if there is a group in the session</returns> public bool CurrentGroupExists() { bool action = false; try { if ( CurrentGroup != null && CurrentGroup.Id > 0 ) { action = true; } else { if ( IsTestEnv() ) { //populate a default current group to allow component testing //get manager //MyManager myManager = new MyManager(); //CurrentGroup = myManager.GetLowestGroup(); //if ( CurrentGroup != null && CurrentGroup.Id > 0 ) //{ // action = true; //} } } } catch { } return action; } // /// <summary> /// Get current group from session /// </summary> /// <returns></returns> public AppGroup GetCurrentGroup() { AppGroup entity = new AppGroup(); try { if ( CurrentGroup == null ) { //set some defaults?? entity.Title = "Missing"; //initialize session CurrentGroup = entity; } else { entity = CurrentGroup; } } catch { } return entity; } // /// <summary> /// Set a new current group /// - ensures we have any updates and access to columns that are not part of the interface /// </summary> /// <returns></returns> public bool SetCurrentGroup( int id, ref string statusMessage ) { CurrentGroup = new AppGroup(); bool action = true; try { //GroupManager manager = new GroupManager(); CurrentGroup = Get( id ); } catch ( Exception ex ) { action = false; string msg = "Unexpected error encountered while attempting to set a new current group to group id = " + id.ToString() + ". "; LogError( ex, thisClassName + ".SetCurrentGroup() - " + msg ); statusMessage = msg + "<br/>System administration has been notified:<br/> " + ex.Message.ToString(); } return action; } // /// <summary> /// Update the current group /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool UpdateCurrentGroup( AppGroup entity, ref string statusMessage ) { bool action = true; try { //update the group with the orgId //GroupManager manager = new GroupManager(); entity.LastUpdated = System.DateTime.Now; //entity.LastUpdatedBy = WebUser.FullName(); //entity.LastUpdatedById = WebUser.Id; statusMessage = Update( entity ); //refresh group - not sure if necessary here as latter are the only changes CurrentGroup = Get( entity.Id ); } catch ( Exception ex ) { action = false; LogError( ex, thisClassName + ".UpdateCurrentGroup() - Unexpected error encountered while attempting to update the current group." ); statusMessage = "An unexpected error was encountered while attempting to update the current group. System administration has been notified:<br/> " + ex.Message.ToString(); } return action; }// #endregion #region Group Members public static bool GroupMember_Delete( int id, ref string statusMessage ) { return GroupMemberManager.Delete( id, ref statusMessage ); }// public static int GroupMember_Create( GroupMember entity, ref string statusMessage ) { return GroupMemberManager.Create( entity, ref statusMessage ); }// public static DataSet GroupMember_Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows ) { return GroupMemberManager.Search( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows ); }// #endregion #region Org Group Members public static bool GroupOrgMember_Delete( int id, ref string statusMessage ) { bool action = false; EFDAL.GatewayContext ctx = new EFDAL.GatewayContext(); EFDAL.AppGroup_OrgMember entity = ctx.AppGroup_OrgMember.SingleOrDefault( s => s.ID == id ); if ( entity != null ) { ctx.AppGroup_OrgMember.Remove( entity ); ctx.SaveChanges(); action = true; } return action; }// public static int GroupOrgMember_Create( GroupOrgMember gom, ref string statusMessage ) { EFDAL.GatewayContext ctx = new EFDAL.GatewayContext(); //entity = OrganizationMember_FromMap( gom ); EFDAL.AppGroup_OrgMember to = new EFDAL.AppGroup_OrgMember(); to.GroupId = gom.GroupId; to.OrgId = gom.OrgId; to.IsActive = true; to.LastUpdatedById = gom.CreatedById; to.Created = System.DateTime.Now; to.LastUpdatedById = gom.CreatedById; to.LastUpdated = System.DateTime.Now; to.RowId = Guid.NewGuid(); ctx.AppGroup_OrgMember.Add( to ); // submit the change to database int count = ctx.SaveChanges(); if ( count > 0 ) { statusMessage = "Successful"; return to.ID; } else { statusMessage = "Error - GroupOrgMember_Create failed"; //?no info on error return 0; } }// public static DataSet GroupOrgMember_Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows ) { return GroupMemberManager.GroupOrgMbrSearch( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows ); }// #endregion #region Privileges public static ApplicationRolePrivilege GetGroupObjectPrivileges( IWebUser currentUser, string pObjectName ) { return SecurityManager.GetGroupObjectPrivileges( currentUser, pObjectName ); }// public static ApplicationRolePrivilege GetGroupObjectPrivileges( AppUser currentUser, string pObjectName ) { return SecurityManager.GetGroupObjectPrivileges( currentUser, pObjectName ); }// #endregion #region organization group authorization ==> Temp /// <summary> /// retrieve list of approvers for an org /// </summary> /// <param name="pOrgId"></param> /// <returns></returns> public static List<GroupMember> OrgApproversSelect( int pOrgId ) { return GroupMemberManager.OrgApproversSelect( pOrgId ); }// /// <summary> /// return true, if user can approve the passed orgId /// </summary> /// <param name="pOrgId"></param> /// <param name="userId"></param> /// <returns></returns> public static bool IsUserAnOrgApprover( int pOrgId, int userId ) { return GroupMemberManager.IsUserAnOrgApprover( pOrgId, userId ); }// public static bool IsUserAnyOrgApprover( int userId ) { string code = "OrgApprovers"; return GroupMemberManager.IsAGroupMember( code, userId ); }// /// <summary> /// TODO - list of all orgs where user is an approver - useful for searches /// </summary> /// <param name="userId"></param> /// <returns></returns> public static List<Organization> ApproverOrgsSelect( int userId ) { List<Organization> list = new List<Organization>(); return list; //GroupMemberManager.OrgApproversSelect( userId ); }// #endregion #region Codes public static List<CodeItem> GroupTypeCodes_Select() { return EFDAL.GroupsManager.Codes_GroupType_Get(); }// public static DataSet CodesGroupType_Select() { DataSet ds = DatabaseManager.DoQuery("SELECT [Id],[Title] FROM [Gateway].[dbo].[Codes.GroupType] order by [Title]"); return ds; //GroupMemberManager.OrgApproversSelect( userId ); }// #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using System.Collections.Generic; using System.Threading; namespace OpenSim.Framework { /// <summary> /// Manage client circuits /// </summary> public class AgentCircuitManager { /// <summary> /// Agent circuits indexed by circuit code. /// </summary> /// <remarks> /// We lock this for operations both on this dictionary and on m_agentCircuitsByUUID /// </remarks> private Dictionary<uint, AgentCircuitData> m_agentCircuits = new Dictionary<uint, AgentCircuitData>(); private ReaderWriterLock m_AgentCircuitsLock = new ReaderWriterLock(); /// <summary> /// Agent circuits indexed by agent UUID. /// </summary> private Dictionary<UUID, AgentCircuitData> m_agentCircuitsByUUID = new Dictionary<UUID, AgentCircuitData>(); /// <summary> /// Add information about a new circuit so that later on we can authenticate a new client session. /// </summary> /// <param name="circuitCode"></param> /// <param name="agentData"></param> public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData) { m_AgentCircuitsLock.AcquireWriterLock(-1); try { if (m_agentCircuits.ContainsKey(circuitCode)) { m_agentCircuits[circuitCode] = agentData; m_agentCircuitsByUUID[agentData.AgentID] = agentData; } else { m_agentCircuits.Add(circuitCode, agentData); m_agentCircuitsByUUID[agentData.AgentID] = agentData; } } finally { m_AgentCircuitsLock.ReleaseWriterLock(); } } public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode) { AgentCircuitData validcircuit = null; m_AgentCircuitsLock.AcquireReaderLock(-1); try { if (m_agentCircuits.ContainsKey(circuitcode)) validcircuit = m_agentCircuits[circuitcode]; } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } AuthenticateResponse user = new AuthenticateResponse(); if (validcircuit == null) { //don't have this circuit code in our list user.Authorised = false; return user; } if ((sessionID == validcircuit.SessionID) && (agentID == validcircuit.AgentID)) { user.Authorised = true; user.LoginInfo = new Login(); user.LoginInfo.Agent = agentID; user.LoginInfo.Session = sessionID; user.LoginInfo.SecureSession = validcircuit.SecureSessionID; user.LoginInfo.First = validcircuit.firstname; user.LoginInfo.Last = validcircuit.lastname; user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder; user.LoginInfo.BaseFolder = validcircuit.BaseFolder; user.LoginInfo.StartPos = validcircuit.startpos; } else { // Invalid user.Authorised = false; } return user; } public bool GetAgentChildStatus(uint circuitcode) { m_AgentCircuitsLock.AcquireReaderLock(-1); try { if (m_agentCircuits.ContainsKey(circuitcode)) return m_agentCircuits[circuitcode].child; } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } return false; } public AgentCircuitData GetAgentCircuitData(uint circuitCode) { AgentCircuitData agentCircuit = null; m_AgentCircuitsLock.AcquireReaderLock(-1); try { m_agentCircuits.TryGetValue(circuitCode, out agentCircuit); } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } return agentCircuit; } public AgentCircuitData GetAgentCircuitData(UUID agentID) { AgentCircuitData agentCircuit = null; m_AgentCircuitsLock.AcquireReaderLock(-1); try { m_agentCircuitsByUUID.TryGetValue(agentID, out agentCircuit); } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } return agentCircuit; } /// <summary> /// Get all current agent circuits indexed by agent UUID. /// </summary> /// <returns></returns> public Dictionary<UUID, AgentCircuitData> GetAgentCircuits() { m_AgentCircuitsLock.AcquireReaderLock(-1); try { return new Dictionary<UUID, AgentCircuitData>(m_agentCircuitsByUUID); } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } } public virtual void RemoveCircuit(uint circuitCode) { m_AgentCircuitsLock.AcquireWriterLock(-1); try { if (m_agentCircuits.ContainsKey(circuitCode)) { UUID agentID = m_agentCircuits[circuitCode].AgentID; m_agentCircuits.Remove(circuitCode); m_agentCircuitsByUUID.Remove(agentID); } } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } } public virtual void RemoveCircuit(UUID agentID) { m_AgentCircuitsLock.AcquireWriterLock(-1); try { if (m_agentCircuitsByUUID.ContainsKey(agentID)) { uint circuitCode = m_agentCircuitsByUUID[agentID].circuitcode; m_agentCircuits.Remove(circuitCode); m_agentCircuitsByUUID.Remove(agentID); } } finally { m_AgentCircuitsLock.ReleaseWriterLock(); } } /// <summary> /// Sometimes the circuitcode may not be known before setting up the connection /// </summary> /// <param name="circuitcode"></param> /// <param name="newcircuitcode"></param> public bool TryChangeCiruitCode(uint circuitcode, uint newcircuitcode) { m_AgentCircuitsLock.AcquireWriterLock(-1); try { if (m_agentCircuits.ContainsKey((uint)circuitcode) && !m_agentCircuits.ContainsKey((uint)newcircuitcode)) { AgentCircuitData agentData = m_agentCircuits[(uint)circuitcode]; agentData.circuitcode = newcircuitcode; m_agentCircuits.Remove((uint)circuitcode); m_agentCircuits.Add(newcircuitcode, agentData); return true; } } finally { m_AgentCircuitsLock.ReleaseWriterLock(); } return false; } public void UpdateAgentChildStatus(uint circuitcode, bool childstatus) { m_AgentCircuitsLock.AcquireReaderLock(-1); try { if (m_agentCircuits.ContainsKey(circuitcode)) m_agentCircuits[circuitcode].child = childstatus; } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } } public void UpdateAgentData(AgentCircuitData agentData) { m_AgentCircuitsLock.AcquireReaderLock(-1); try { if (m_agentCircuits.ContainsKey((uint)agentData.circuitcode)) { m_agentCircuits[(uint)agentData.circuitcode].firstname = agentData.firstname; m_agentCircuits[(uint)agentData.circuitcode].lastname = agentData.lastname; m_agentCircuits[(uint)agentData.circuitcode].startpos = agentData.startpos; // Updated for when we don't know them before calling Scene.NewUserConnection m_agentCircuits[(uint)agentData.circuitcode].SecureSessionID = agentData.SecureSessionID; m_agentCircuits[(uint)agentData.circuitcode].SessionID = agentData.SessionID; // m_log.Debug("update user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z); } } finally { m_AgentCircuitsLock.ReleaseReaderLock(); } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq.Provider; using System.Linq; using System.Data.Linq.SqlClient; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.SqlClient { // duplicates an expression up until a column or column ref is encountered // goes 'deep' through alias ref's // assumes that columnizing has been done already internal class SqlExpander { SqlFactory factory; internal SqlExpander(SqlFactory factory) { this.factory = factory; } internal SqlExpression Expand(SqlExpression exp) { return (new Visitor(this.factory)).VisitExpression(exp); } class Visitor : SqlDuplicator.DuplicatingVisitor { SqlFactory factory; Expression sourceExpression; internal Visitor(SqlFactory factory) : base(true) { this.factory = factory; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { return cref; } internal override SqlExpression VisitColumn(SqlColumn col) { return new SqlColumnRef(col); } internal override SqlExpression VisitSharedExpression(SqlSharedExpression shared) { return this.VisitExpression(shared.Expression); } internal override SqlExpression VisitSharedExpressionRef(SqlSharedExpressionRef sref) { return this.VisitExpression(sref.SharedExpression.Expression); } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { SqlNode node = aref.Alias.Node; if (node is SqlTable || node is SqlTableValuedFunctionCall) { return aref; } SqlUnion union = node as SqlUnion; if (union != null) { return this.ExpandUnion(union); } SqlSelect ss = node as SqlSelect; if (ss != null) { return this.VisitExpression(ss.Selection); } SqlExpression exp = node as SqlExpression; if (exp != null) return this.VisitExpression(exp); throw Error.CouldNotHandleAliasRef(node.NodeType); } internal override SqlExpression VisitSubSelect(SqlSubSelect ss) { return (SqlExpression)new SqlDuplicator().Duplicate(ss); } internal override SqlNode VisitLink(SqlLink link) { SqlExpression expansion = this.VisitExpression(link.Expansion); SqlExpression[] exprs = new SqlExpression[link.KeyExpressions.Count]; for (int i = 0, n = exprs.Length; i < n; i++) { exprs[i] = this.VisitExpression(link.KeyExpressions[i]); } return new SqlLink(link.Id, link.RowType, link.ClrType, link.SqlType, link.Expression, link.Member, exprs, expansion, link.SourceExpression); } private SqlExpression ExpandUnion(SqlUnion union) { List<SqlExpression> exprs = new List<SqlExpression>(2); this.GatherUnionExpressions(union, exprs); this.sourceExpression = union.SourceExpression; SqlExpression result = this.ExpandTogether(exprs); return result; } private void GatherUnionExpressions(SqlNode node, List<SqlExpression> exprs) { SqlUnion union = node as SqlUnion; if (union != null) { this.GatherUnionExpressions(union.Left, exprs); this.GatherUnionExpressions(union.Right, exprs); } else { SqlSelect sel = node as SqlSelect; if (sel != null) { SqlAliasRef aref = sel.Selection as SqlAliasRef; if (aref != null) { this.GatherUnionExpressions(aref.Alias.Node, exprs); } else { exprs.Add(sel.Selection); } } } } [SuppressMessage("Microsoft.Performance", "CA1809:AvoidExcessiveLocals", Justification="These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Justification = "These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] private SqlExpression ExpandTogether(List<SqlExpression> exprs) { switch (exprs[0].NodeType) { case SqlNodeType.MethodCall: { SqlMethodCall[] mcs = new SqlMethodCall[exprs.Count]; for (int i = 0; i < mcs.Length; ++i) { mcs[i] = (SqlMethodCall)exprs[i]; } List<SqlExpression> expandedArgs = new List<SqlExpression>(); for (int i = 0; i < mcs[0].Arguments.Count; ++i) { List<SqlExpression> args = new List<SqlExpression>(); for (int j = 0; j < mcs.Length; ++j) { args.Add(mcs[j].Arguments[i]); } SqlExpression expanded = this.ExpandTogether(args); expandedArgs.Add(expanded); } return factory.MethodCall(mcs[0].Method, mcs[0].Object, expandedArgs.ToArray(), mcs[0].SourceExpression); } case SqlNodeType.ClientCase: { // Are they all the same? SqlClientCase[] scs = new SqlClientCase[exprs.Count]; scs[0] = (SqlClientCase)exprs[0]; for (int i = 1; i < scs.Length; ++i) { scs[i] = (SqlClientCase)exprs[i]; } // Expand expressions together. List<SqlExpression> expressions = new List<SqlExpression>(); for (int i = 0; i < scs.Length; ++i) { expressions.Add(scs[i].Expression); } SqlExpression expression = this.ExpandTogether(expressions); // Expand individual expressions together. List<SqlClientWhen> whens = new List<SqlClientWhen>(); for (int i = 0; i < scs[0].Whens.Count; ++i) { List<SqlExpression> scos = new List<SqlExpression>(); for (int j = 0; j < scs.Length; ++j) { SqlClientWhen when = scs[j].Whens[i]; scos.Add(when.Value); } whens.Add(new SqlClientWhen(scs[0].Whens[i].Match, this.ExpandTogether(scos))); } return new SqlClientCase(scs[0].ClrType, expression, whens, scs[0].SourceExpression); } case SqlNodeType.TypeCase: { // Are they all the same? SqlTypeCase[] tcs = new SqlTypeCase[exprs.Count]; tcs[0] = (SqlTypeCase)exprs[0]; for (int i = 1; i < tcs.Length; ++i) { tcs[i] = (SqlTypeCase)exprs[i]; } // Expand discriminators together. List<SqlExpression> discriminators = new List<SqlExpression>(); for (int i = 0; i < tcs.Length; ++i) { discriminators.Add(tcs[i].Discriminator); } SqlExpression discriminator = this.ExpandTogether(discriminators); // Write expanded discriminators back in. for (int i = 0; i < tcs.Length; ++i) { tcs[i].Discriminator = discriminators[i]; } // Expand individual type bindings together. List<SqlTypeCaseWhen> whens = new List<SqlTypeCaseWhen>(); for (int i = 0; i < tcs[0].Whens.Count; ++i) { List<SqlExpression> scos = new List<SqlExpression>(); for (int j = 0; j < tcs.Length; ++j) { SqlTypeCaseWhen when = tcs[j].Whens[i]; scos.Add(when.TypeBinding); } SqlExpression expanded = this.ExpandTogether(scos); whens.Add(new SqlTypeCaseWhen(tcs[0].Whens[i].Match, expanded)); } return factory.TypeCase(tcs[0].ClrType, tcs[0].RowType, discriminator, whens, tcs[0].SourceExpression); } case SqlNodeType.New: { // first verify all are similar client objects... SqlNew[] cobs = new SqlNew[exprs.Count]; cobs[0] = (SqlNew)exprs[0]; for (int i = 1, n = exprs.Count; i < n; i++) { if (exprs[i] == null || exprs[i].NodeType != SqlNodeType.New) throw Error.UnionIncompatibleConstruction(); cobs[i] = (SqlNew)exprs[1]; if (cobs[i].Members.Count != cobs[0].Members.Count) throw Error.UnionDifferentMembers(); for (int m = 0, mn = cobs[0].Members.Count; m < mn; m++) { if (cobs[i].Members[m].Member != cobs[0].Members[m].Member) { throw Error.UnionDifferentMemberOrder(); } } } SqlMemberAssign[] bindings = new SqlMemberAssign[cobs[0].Members.Count]; for (int m = 0, mn = bindings.Length; m < mn; m++) { List<SqlExpression> mexprs = new List<SqlExpression>(); for (int i = 0, n = exprs.Count; i < n; i++) { mexprs.Add(cobs[i].Members[m].Expression); } bindings[m] = new SqlMemberAssign(cobs[0].Members[m].Member, this.ExpandTogether(mexprs)); for (int i = 0, n = exprs.Count; i < n; i++) { cobs[i].Members[m].Expression = mexprs[i]; } } SqlExpression[] arguments = new SqlExpression[cobs[0].Args.Count]; for (int m = 0, mn = arguments.Length; m < mn; ++m) { List<SqlExpression> mexprs = new List<SqlExpression>(); for (int i = 0, n = exprs.Count; i < n; i++) { mexprs.Add(cobs[i].Args[m]); } arguments[m] = ExpandTogether(mexprs); } return factory.New(cobs[0].MetaType, cobs[0].Constructor, arguments, cobs[0].ArgMembers, bindings, exprs[0].SourceExpression); } case SqlNodeType.Link: { SqlLink[] links = new SqlLink[exprs.Count]; links[0] = (SqlLink)exprs[0]; for (int i = 1, n = exprs.Count; i < n; i++) { if (exprs[i] == null || exprs[i].NodeType != SqlNodeType.Link) throw Error.UnionIncompatibleConstruction(); links[i] = (SqlLink)exprs[i]; if (links[i].KeyExpressions.Count != links[0].KeyExpressions.Count || links[i].Member != links[0].Member || (links[i].Expansion != null) != (links[0].Expansion != null)) throw Error.UnionIncompatibleConstruction(); } SqlExpression[] kexprs = new SqlExpression[links[0].KeyExpressions.Count]; List<SqlExpression> lexprs = new List<SqlExpression>(); for (int k = 0, nk = links[0].KeyExpressions.Count; k < nk; k++) { lexprs.Clear(); for (int i = 0, n = exprs.Count; i < n; i++) { lexprs.Add(links[i].KeyExpressions[k]); } kexprs[k] = this.ExpandTogether(lexprs); for (int i = 0, n = exprs.Count; i < n; i++) { links[i].KeyExpressions[k] = lexprs[i]; } } SqlExpression expansion = null; if (links[0].Expansion != null) { lexprs.Clear(); for (int i = 0, n = exprs.Count; i < n; i++) { lexprs.Add(links[i].Expansion); } expansion = this.ExpandTogether(lexprs); for (int i = 0, n = exprs.Count; i < n; i++) { links[i].Expansion = lexprs[i]; } } return new SqlLink(links[0].Id, links[0].RowType, links[0].ClrType, links[0].SqlType, links[0].Expression, links[0].Member, kexprs, expansion, links[0].SourceExpression); } case SqlNodeType.Value: { /* * ExprSet of all literals of the same value reduce to just a single literal. */ SqlValue val0 = (SqlValue)exprs[0]; for (int i = 1; i < exprs.Count; ++i) { SqlValue val = (SqlValue)exprs[i]; if (!object.Equals(val.Value, val0.Value)) return this.ExpandIntoExprSet(exprs); } return val0; } case SqlNodeType.OptionalValue: { if (exprs[0].SqlType.CanBeColumn) { goto default; } List<SqlExpression> hvals = new List<SqlExpression>(exprs.Count); List<SqlExpression> vals = new List<SqlExpression>(exprs.Count); for (int i = 0, n = exprs.Count; i < n; i++) { if (exprs[i] == null || exprs[i].NodeType != SqlNodeType.OptionalValue) { throw Error.UnionIncompatibleConstruction(); } SqlOptionalValue sov = (SqlOptionalValue)exprs[i]; hvals.Add(sov.HasValue); vals.Add(sov.Value); } return new SqlOptionalValue(this.ExpandTogether(hvals), this.ExpandTogether(vals)); } case SqlNodeType.OuterJoinedValue: { if (exprs[0].SqlType.CanBeColumn) { goto default; } List<SqlExpression> values = new List<SqlExpression>(exprs.Count); for (int i = 0, n = exprs.Count; i < n; i++) { if (exprs[i] == null || exprs[i].NodeType != SqlNodeType.OuterJoinedValue) { throw Error.UnionIncompatibleConstruction(); } SqlUnary su = (SqlUnary)exprs[i]; values.Add(su.Operand); } return factory.Unary(SqlNodeType.OuterJoinedValue, this.ExpandTogether(values)); } case SqlNodeType.DiscriminatedType: { SqlDiscriminatedType sdt0 = (SqlDiscriminatedType)exprs[0]; List<SqlExpression> foos = new List<SqlExpression>(exprs.Count); foos.Add(sdt0.Discriminator); for (int i = 1, n = exprs.Count; i < n; i++) { SqlDiscriminatedType sdtN = (SqlDiscriminatedType)exprs[i]; if (sdtN.TargetType != sdt0.TargetType) { throw Error.UnionIncompatibleConstruction(); } foos.Add(sdtN.Discriminator); } return factory.DiscriminatedType(this.ExpandTogether(foos), ((SqlDiscriminatedType)exprs[0]).TargetType); } case SqlNodeType.ClientQuery: case SqlNodeType.Multiset: case SqlNodeType.Element: case SqlNodeType.Grouping: throw Error.UnionWithHierarchy(); default: return this.ExpandIntoExprSet(exprs); } } /// <summary> /// Expand a set of expressions into a single expr set. /// This is typically a fallback when there is no other way to unify a set of expressions. /// </summary> private SqlExpression ExpandIntoExprSet(List<SqlExpression> exprs) { SqlExpression[] rexprs = new SqlExpression[exprs.Count]; for (int i = 0, n = exprs.Count; i < n; i++) { rexprs[i] = this.VisitExpression(exprs[i]); } return this.factory.ExprSet(rexprs, this.sourceExpression); } } } }
using System.Collections.Generic; using System.Xml.Linq; using NUnit.Framework; using Is = SIL.TestUtilities.NUnitExtensions.Is; using SIL.WritingSystems; namespace SIL.Lexicon.Tests { [TestFixture] public class ProjectLexiconSettingsWritingSystemDataMapperTests { [Test] public void Read_ValidXml_SetsAllProperties() { const string projectSettingsXml = @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> <SystemCollation>snarf</SystemCollation> </WritingSystem> <WritingSystem id=""fr-FR""> <SpellCheckingId>fr_FR</SpellCheckingId> <LegacyMapping>converter</LegacyMapping> <Keyboard>Old Keyboard</Keyboard> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>"; var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(new MemorySettingsStore {SettingsElement = XElement.Parse(projectSettingsXml)}); var ws1 = new WritingSystemDefinition("qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2"); projectSettingsDataMapper.Read(ws1); Assert.That(ws1.Abbreviation, Is.EqualTo("kal")); Assert.That(ws1.Language.Name, Is.EqualTo("Kalaba")); Assert.That(ws1.Script.Name, Is.EqualTo("Fake")); Assert.That(ws1.Region.Name, Is.EqualTo("Zolrog")); Assert.That(ws1.SpellCheckingId, Is.EqualTo(string.Empty)); Assert.That(ws1.LegacyMapping, Is.EqualTo(string.Empty)); Assert.That(ws1.Keyboard, Is.EqualTo(string.Empty)); var scd = new SystemCollationDefinition {LanguageTag = "snarf"}; Assert.That(ws1.DefaultCollation, Is.ValueEqualTo(scd)); var ws2 = new WritingSystemDefinition("fr-FR"); projectSettingsDataMapper.Read(ws2); Assert.That(ws2.Abbreviation, Is.EqualTo("fr")); Assert.That(ws2.Language.Name, Is.EqualTo("French")); Assert.That(ws2.Script.Name, Is.EqualTo("Latin")); Assert.That(ws2.Region.Name, Is.EqualTo("France")); Assert.That(ws2.Variants, Is.Empty); Assert.That(ws2.SpellCheckingId, Is.EqualTo("fr_FR")); Assert.That(ws2.LegacyMapping, Is.EqualTo("converter")); Assert.That(ws2.Keyboard, Is.EqualTo("Old Keyboard")); var ws3 = new WritingSystemDefinition("es"); projectSettingsDataMapper.Read(ws3); Assert.That(ws3.Abbreviation, Is.EqualTo("es")); Assert.That(ws3.Language.Name, Is.EqualTo("Spanish")); Assert.That(ws3.Script.Name, Is.EqualTo("Latin")); Assert.That(ws3.Region, Is.Null); Assert.That(ws3.Variants, Is.Empty); Assert.That(ws3.SpellCheckingId, Is.EqualTo(string.Empty)); Assert.That(ws3.LegacyMapping, Is.EqualTo(string.Empty)); Assert.That(ws3.Keyboard, Is.EqualTo(string.Empty)); } [Test] public void Read_EmptyXml_NothingSet() { var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(new MemorySettingsStore()); var ws1 = new WritingSystemDefinition("en-US"); projectSettingsDataMapper.Read(ws1); Assert.That(ws1.Abbreviation, Is.EqualTo("en")); Assert.That(ws1.Language.Name, Is.EqualTo("English")); Assert.That(ws1.Script.Name, Is.EqualTo("Latin")); Assert.That(ws1.Region.Name, Is.EqualTo("United States")); Assert.That(ws1.Variants, Is.Empty); Assert.That(ws1.SpellCheckingId, Is.EqualTo(string.Empty)); Assert.That(ws1.LegacyMapping, Is.EqualTo(string.Empty)); Assert.That(ws1.Keyboard, Is.EqualTo(string.Empty)); } [Test] public void Write_EmptyXml_XmlUpdated() { var settingsStore = new MemorySettingsStore(); var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(settingsStore); var ws1 = new WritingSystemDefinition("qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2"); ws1.Language = new LanguageSubtag(ws1.Language, "Kalaba"); ws1.Script = new ScriptSubtag(ws1.Script, "Fake"); ws1.Region = new RegionSubtag(ws1.Region, "Zolrog"); ws1.Variants[0] = new VariantSubtag(ws1.Variants[0], "Custom 1"); ws1.Variants[1] = new VariantSubtag(ws1.Variants[1], "Custom 2"); projectSettingsDataMapper.Write(ws1); Assert.That(settingsStore.SettingsElement, Is.XmlEqualTo( @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>")); } [Test] public void Write_ValidXml_XmlUpdated() { const string projectSettingsXml = @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2-var3""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>"; var settingsStore = new MemorySettingsStore {SettingsElement = XElement.Parse(projectSettingsXml)}; var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(settingsStore); var ws1 = new WritingSystemDefinition("qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2-var3"); ws1.Abbreviation = "ka"; ws1.SpellCheckingId = "en_US"; ws1.LegacyMapping = "converter"; ws1.Keyboard = "Old Keyboard"; var scd = new SystemCollationDefinition {LanguageTag = "snarf"}; ws1.DefaultCollation = scd; projectSettingsDataMapper.Write(ws1); Assert.That(settingsStore.SettingsElement, Is.XmlEqualTo( @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2-var3""> <Abbreviation>ka</Abbreviation> <SpellCheckingId>en_US</SpellCheckingId> <LegacyMapping>converter</LegacyMapping> <Keyboard>Old Keyboard</Keyboard> <SystemCollation>snarf</SystemCollation> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>")); } [Test] public void Remove_ExistingWritingSystem_UpdatesXml() { const string projectSettingsXml = @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> <VariantNames> <VariantName>Custom 1</VariantName> <VariantName>Custom 2</VariantName> </VariantNames> </WritingSystem> <WritingSystem id=""fr-FR""> <SpellCheckingId>fr_FR</SpellCheckingId> <LegacyMapping>converter</LegacyMapping> <Keyboard>Old Keyboard</Keyboard> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>"; var settingsStore = new MemorySettingsStore {SettingsElement = XElement.Parse(projectSettingsXml)}; var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(settingsStore); projectSettingsDataMapper.Remove("fr-FR"); Assert.That(settingsStore.SettingsElement, Is.XmlEqualTo( @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> <VariantNames> <VariantName>Custom 1</VariantName> <VariantName>Custom 2</VariantName> </VariantNames> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>")); projectSettingsDataMapper.Remove("qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2"); Assert.That(settingsStore.SettingsElement, Is.XmlEqualTo("<ProjectLexiconSettings />")); } [Test] public void Remove_FinalWritingSystem_PreservesSettings() { const string projectSettingsXml = @"<ProjectLexiconSettings> <WritingSystems addToSldr=""true""> <WritingSystem id=""fr-FR""> <SpellCheckingId>fr_FR</SpellCheckingId> <LegacyMapping>converter</LegacyMapping> <Keyboard>Old Keyboard</Keyboard> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>"; var settingsStore = new MemorySettingsStore {SettingsElement = XElement.Parse(projectSettingsXml)}; var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(settingsStore); projectSettingsDataMapper.Remove("fr-FR"); Assert.That(settingsStore.SettingsElement, Is.EqualTo(XElement.Parse( @"<ProjectLexiconSettings> <WritingSystems addToSldr=""true""/> </ProjectLexiconSettings>")).Using((IEqualityComparer<XNode>) new XNodeEqualityComparer())); } [Test] public void Remove_NonexistentWritingSystem_DoesNotUpdateFile() { const string projectSettingsXml = @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> <VariantNames> <VariantName>Custom 1</VariantName> <VariantName>Custom 2</VariantName> </VariantNames> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>"; var settingsStore = new MemorySettingsStore {SettingsElement = XElement.Parse(projectSettingsXml)}; var projectSettingsDataMapper = new ProjectLexiconSettingsWritingSystemDataMapper(settingsStore); projectSettingsDataMapper.Remove("fr-FR"); Assert.That(settingsStore.SettingsElement, Is.XmlEqualTo( @"<ProjectLexiconSettings> <WritingSystems> <WritingSystem id=""qaa-Qaaa-QM-x-kal-Fake-ZG-var1-var2""> <Abbreviation>kal</Abbreviation> <LanguageName>Kalaba</LanguageName> <ScriptName>Fake</ScriptName> <RegionName>Zolrog</RegionName> <VariantNames> <VariantName>Custom 1</VariantName> <VariantName>Custom 2</VariantName> </VariantNames> </WritingSystem> </WritingSystems> </ProjectLexiconSettings>")); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using ProtoBuf; using Riemann.Proto; using Attribute = Riemann.Proto.Attribute; namespace Riemann { /// /// <summary>Client represents a connection to the Riemann service.</summary> /// public class Client : IDisposable, IClient { private RiemannTags _tag; private readonly object _tagLock = new object(); private class RiemannTags : IDisposable { private readonly Client _owner; private readonly RiemannTags _underlying; private readonly string _tag; public RiemannTags(Client owner, RiemannTags underlying, string tag) { _owner = owner; _underlying = underlying; _tag = tag; } public void Dispose() { _owner._tag = _underlying; } public IEnumerable<string> Tags { get { if (_underlying != null) { foreach (var tag in _underlying.Tags) { yield return tag; } } yield return _tag; } } } private readonly string _host; private readonly ushort _port; private readonly string _name = GetFqdn(); private readonly bool _throwExceptionsOnTicks; private readonly bool _useTcp; private readonly CancellationTokenSource _cancellationTokenSource; public enum State { Disconnected, Connecting, Connected, Disconnecting }; public bool SuppressSendErrors { get; set; } public State ConnectionState = State.Disconnected; private static string GetFqdn() { var properties = IPGlobalProperties.GetIPGlobalProperties(); return string.Format("{0}.{1}", properties.HostName, properties.DomainName); } /// /// <summary>Constructs a new Client with the specified host, port</summary> /// <param name='host'>Remote hostname to connect to. Default: localhost</param> /// <param name='port'>Port to connect to. Default: 5555</param> /// <param name='throwExceptionOnTicks'>Throw an exception on the background thread managing the TickEvents. Default: true</param> /// <param name="useTcp">Use TCP for transport (UDP otherwise). Default: false</param> /// public Client(string host = "localhost", int port = 5555, bool throwExceptionOnTicks = true, bool useTcp = false) { SuppressSendErrors = true; _host = host; _port = (ushort) port; _throwExceptionsOnTicks = throwExceptionOnTicks; _useTcp = useTcp; if (_useTcp) { _cancellationTokenSource = new CancellationTokenSource(); var token = _cancellationTokenSource.Token; Task.Run(async () => { while (!token.IsCancellationRequested) { try { lock (this) { if (_tcpStream == null || _tcpSocket == null || !_tcpSocket.Connected) { OpenTcpConnectionUnsafe(); } } } catch (Exception) {} await Task.Delay(5000); } }, token); } else { OpenUdpConnection(); } } /// /// <summary>Adds a tag to the current context (relative to this client). This call is not thread-safe.</summary> /// <param name='tag'>New tag to add to the Riemann events sent using this client.</param> /// public IDisposable Tag(string tag) { lock (_tagLock) { _tag = new RiemannTags(this, _tag, tag); return _tag; } } private class TickDisposable : IDisposable { public readonly int TickTime; public readonly string Service; public int NextTick; public bool RemoveRequested; private readonly Func<TickEvent> _onTick; public TickDisposable(int tickTime, string service, Func<TickEvent> onTick) { TickTime = tickTime; Service = service; _onTick = onTick; } public void Dispose() { RemoveRequested = true; } public TickEvent Tick() { return _onTick(); } } private readonly object _timerLock = new object(); private Timer _timer; private List<TickDisposable> _ticks; /// /// <summary> /// After <paramref name="tickTimeInSeconds" /> seconds, <paramref name="onTick" /> will be invoked. /// The resulting <see cref="TickEvent" /> is composed with the <paramref name="service" /> to generate an Event. /// </summary> /// <param name="tickTimeInSeconds"> /// Number of seconds to wait before calling the event back. /// <note>Because only a single thread calls the events back, it may be called back sooner.</note> /// </param> /// <param name="service">Name of the service to send to Riemann</param> /// <param name="onTick">Function to call back after wait period</param> /// <returns> /// A disposable that, if called, will remove this callback from getting called. /// <note>An additional tick may elapse after removal, due to the multithreaded nature.</note> /// </returns> public IDisposable Tick(int tickTimeInSeconds, string service, Func<TickEvent> onTick) { var disposable = new TickDisposable(tickTimeInSeconds, service, onTick); lock(_timerLock) { if (_ticks == null) { _ticks = new List<TickDisposable>(); _timer = new Timer(_=> ProcessTicks()); _timer.Change(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0)); } _ticks.Add(disposable); } return disposable; } private void ProcessTicks() { try { var events = new List<Event>(); List<TickDisposable> ticks; lock (_timerLock) { ticks = _ticks.ToList(); } var removals = new List<TickDisposable>(); foreach (var tick in ticks) { if (tick.RemoveRequested) { removals.Add(tick); } tick.NextTick = tick.NextTick - 1; if (tick.NextTick <= 0) { var t = tick.Tick(); var tickTags = new List<string>(); if (t.Tags != null) { tickTags.AddRange(t.Tags); } events.Add(new Event(tick.Service, t.State, t.Description, t.MetricValue, t.TTL.HasValue ? t.TTL.Value : tick.TickTime * 2, tickTags)); tick.NextTick = tick.TickTime; } } if (removals.Count > 0) { lock (_timerLock) { if (removals.Count == _ticks.Count) { _ticks = null; _timer.Dispose(); _timer = null; } else { foreach (var removal in removals) { _ticks.Remove(removal); } } } } if (events.Count > 0) { SendEvents(events); } } catch { if (_throwExceptionsOnTicks) throw; } } private Socket _tcpSocket; private Stream _tcpStream; private Socket _udpSocket; private const SocketError SocketErrorMessageTooLong = SocketError.MessageSize; private void OpenTcpConnectionUnsafe() { if (ConnectionState != State.Disconnected) { return; } try { ConnectionState = State.Connecting; _tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _tcpSocket.Connect(_host, _port); ConnectionState = State.Connected; _tcpStream = new NetworkStream(_tcpSocket, true); } catch (Exception) { _tcpSocket = null; _tcpStream = null; ConnectionState = State.Disconnected; } } private void OpenUdpConnection() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Connect(_host, _port); _udpSocket = socket; } /// /// <summary>Send many events to Riemann at once.</summary> /// <param name="events"> /// Enumerable of the events to process. /// Enumerable will be enumerated after being passed in. /// </param> /// public void SendEvents(IEnumerable<Event> events) { var tags = new List<string>(); lock (_tagLock) { if (_tag != null) { tags = _tag.Tags.ToList(); } } var protoEvents = events.Select( e => { var evnt = new Proto.Event { host = e.Host ?? _name, service = e.Service, state = e.State, description = e.Description, metric_f = e.Metric, ttl = e.TTL }; evnt.attributes.AddRange( e.Attributes.Select(a => new Attribute {key = a.Key, value = a.Value})); evnt.tags.AddRange(e.Tags); return evnt; }).ToList(); var message = new Msg(); foreach (var protoEvent in protoEvents) { protoEvent.tags.AddRange(tags); message.events.Add(protoEvent); } if (_useTcp) { SendReceiveTcpMsg(message); } else { SendUdpMessage(message); } } private void SendReceiveTcpMsg(Msg msg) { lock (this) { if (ConnectionState == State.Connected) { try { WriteMsgToStream(msg); ReadReplyFromStream(); } catch (IOException) { if (!_tcpSocket.Connected) { ConnectionState = State.Disconnected; _tcpSocket = null; _tcpStream = null; } if (!SuppressSendErrors) { throw; } } } else if (!SuppressSendErrors) { throw new IOException("Not connected"); } } } private void WriteMsgToStream(Msg msg) { Serializer.SerializeWithLengthPrefix(_tcpStream, msg, PrefixStyle.Fixed32BigEndian); } private void ReadReplyFromStream() { Serializer.DeserializeWithLengthPrefix<Msg>(_tcpStream, PrefixStyle.Fixed32BigEndian); } private static byte[] MessageBytes(Msg message) { using (var memoryStream = new MemoryStream()) { Serializer.Serialize(memoryStream, message); return memoryStream.ToArray(); } } private void SendUdpMessage(Msg message) { try { var bytes = MessageBytes(message); _udpSocket.Send(bytes); } catch (Exception) { if (!SuppressSendErrors) { throw; } } } /// <summary>Send a single event to Riemann; assumes that the local host originated the event</summary> /// <param name='service'>Name of the service to push.</param> /// <param name='state'>State of the service; usual values are "ok", "critical", "warning"</param> /// <param name='description'> /// A description of the current state, if applicable. /// Use null or an empty string to denote no additional information. /// </param> /// <param name='metric'>A value related to the service.</param> /// <param name='ttl'>Number of seconds this event will be applicable for.</param> /// <param name="tags">List of tags to associate with this event</param> /// <param name="attributes">Optional arbitrary custom name/value content</param> public void SendEvent(string service, string state, string description, float metric, int ttl = 0, List<string> tags = null, Dictionary<string, string> attributes = null) { SendEvent(null, service, state, description, metric, ttl, tags, attributes); } /// <summary>Send a single event to Riemann.</summary> /// <param name="host">Originating server</param> /// <param name='service'>Name of the service to push.</param> /// <param name='state'>State of the service; usual values are "ok", "critical", "warning"</param> /// <param name='description'> /// A description of the current state, if applicable. /// Use null or an empty string to denote no additional information. /// </param> /// <param name='metric'>A value related to the service.</param> /// <param name='ttl'>Number of seconds this event will be applicable for.</param> /// <param name="tags">List of tags to associate with this event</param> /// <param name="attributes">Optional arbitrary custom name/value content</param> public void SendEvent(string host, string service, string state, string description, float metric, int ttl = 0, List<string> tags = null, Dictionary<string, string> attributes = null) { var ev = new Event(host, service, state, description, metric, ttl, tags, attributes); SendEvents(new[] {ev}); } /// /// <summary>Queries Riemann</summary> /// <param name='query'>Query to send Riemann for process</param> /// <returns>List of States that answer the query.</returns> /// public IEnumerable<Proto.State> Query(string query) { var q = new Proto.Query {@string = query}; var msg = new Proto.Msg {query = q}; Serializer.SerializeWithLengthPrefix(_tcpStream, msg, PrefixStyle.Fixed32BigEndian); var response = Serializer.DeserializeWithLengthPrefix<Msg>(_tcpStream, PrefixStyle.Fixed32BigEndian); if (response.ok) { return response.states; } throw new Exception(response.error); } /// /// <summary>Cleans up state related to this client.</summary> /// public void Dispose() { if (_cancellationTokenSource != null) { _cancellationTokenSource.Cancel(); } if (_tcpStream != null) { _tcpStream.Close(); _tcpStream.Dispose(); } if (_udpSocket != null) { _udpSocket.Close(); _udpSocket.Dispose(); } GC.SuppressFinalize(this); } /// /// <summary>Closes connections.</summary> /// ~Client() { Dispose(); } } }
using System; using System.Threading.Tasks; using AllReady.Models; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; namespace AllReady.Security { public class AuthorizableTaskBuilder : IAuthorizableTaskBuilder { private readonly AllReadyContext _context; private readonly IMemoryCache _cache; private readonly IUserAuthorizationService _userAuthorizationService; private const string CachePrefix = "AuthorizableTask_"; public AuthorizableTaskBuilder(AllReadyContext context, IMemoryCache cache, IUserAuthorizationService userAuthorizationService) { _context = context; _cache = cache; _userAuthorizationService = userAuthorizationService; } /// <inheritdoc /> public async Task<IAuthorizableTask> Build(int taskId, int? eventId = null, int? campaignId = null, int? orgId = null) { IAuthorizableTaskIdContainer cacheAuthorizableTaskIdContainer; if (taskId == 0) { return new NotFoundAuthorizableTask(); } if (_cache.TryGetValue(GetCacheKey(taskId), out cacheAuthorizableTaskIdContainer)) { return new AuthorizableTask(cacheAuthorizableTaskIdContainer, _userAuthorizationService); } int finalEventId; int finalCampaignId; int finalOrgId; if (!HasValidIds(eventId, campaignId, orgId)) { var loadedIds = await _context.VolunteerTasks.AsNoTracking() .Where(x => x.Id == taskId) .Include(x => x.Event).ThenInclude(x => x.Campaign) .Include(x => x.Organization) .FirstOrDefaultAsync(); if (loadedIds == null) { return new NotFoundAuthorizableTask(); } finalEventId = loadedIds.EventId; finalCampaignId = loadedIds.Event.CampaignId; finalOrgId = loadedIds.Organization.Id; } else { finalEventId = eventId.Value; finalCampaignId = campaignId.Value; finalOrgId = orgId.Value; } var authorizedEventIdContainer = new AuthorizableTaskIdContainer(taskId, finalEventId, finalCampaignId, finalOrgId); _cache.Set(GetCacheKey(taskId), authorizedEventIdContainer, TimeSpan.FromHours(1)); // cached for 1 hour return new AuthorizableTask(authorizedEventIdContainer, _userAuthorizationService); } private class AuthorizableTaskIdContainer : IAuthorizableTaskIdContainer { public AuthorizableTaskIdContainer(int taskId, int eventId, int campaignId, int orgId) { TaskId = taskId; EventId = eventId; CampaignId = campaignId; OrganizationId = orgId; } public int TaskId { get; } public int EventId { get; } public int OrganizationId { get; } public int CampaignId { get; } } private static bool HasValidIds(int? eventId, int? campaignId, int? orgId) { if (!eventId.HasValue || !campaignId.HasValue || !orgId.HasValue) { return false; } return eventId.Value != 0 && campaignId.Value != 0 && orgId.Value != 0; } private static string GetCacheKey(int taskId) { return string.Concat(CachePrefix, taskId.ToString()); } private class NotFoundAuthorizableTask : IAuthorizableTask { public int TaskId => 0; public int CampaignId => 0; public int EventId => 0; public int OrganizationId => 0; public Task<bool> UserCanView() { return Task.FromResult(false); } public Task<bool> UserCanEdit() { return Task.FromResult(false); } public Task<bool> UserCanDelete() { return Task.FromResult(false); } } /// <inheritdoc /> private class AuthorizableTask : IAuthorizableTask { private readonly IUserAuthorizationService _userAuthorizationService; public AuthorizableTask(IAuthorizableTaskIdContainer AuthorizableTaskIds, IUserAuthorizationService userAuthorizationService) { _userAuthorizationService = userAuthorizationService; TaskId = AuthorizableTaskIds.TaskId; EventId = AuthorizableTaskIds.EventId; CampaignId = AuthorizableTaskIds.CampaignId; OrganizationId = AuthorizableTaskIds.OrganizationId; } /// <inheritdoc /> public int TaskId { get; } /// <inheritdoc /> public int EventId { get; } /// <inheritdoc /> public int CampaignId { get; } /// <inheritdoc /> public int OrganizationId { get; } private async Task<ItineraryAccessType> UserAccessType() { if (!_userAuthorizationService.HasAssociatedUser) { return ItineraryAccessType.Unauthorized; } if (_userAuthorizationService.IsSiteAdmin) { return ItineraryAccessType.SiteAdmin; } if (_userAuthorizationService.IsOrganizationAdmin(OrganizationId)) { return ItineraryAccessType.OrganizationAdmin; } var managedEventIds = await _userAuthorizationService.GetManagedEventIds(); if (managedEventIds.Contains(EventId)) { return ItineraryAccessType.EventAdmin; } var managedCampaignIds = await _userAuthorizationService.GetManagedCampaignIds(); if (managedCampaignIds.Contains(CampaignId)) { return ItineraryAccessType.CampaignAdmin; } return ItineraryAccessType.Unknown; } /// <inheritdoc /> public Task<bool> UserCanDelete() { return UserCanManage(); } /// <inheritdoc /> public Task<bool> UserCanView() { return UserCanManage(); } /// <inheritdoc /> public Task<bool> UserCanEdit() { return UserCanManage(); } private async Task<bool> UserCanManage() { var userAccessType = await UserAccessType(); return userAccessType == ItineraryAccessType.SiteAdmin || userAccessType == ItineraryAccessType.OrganizationAdmin || userAccessType == ItineraryAccessType.CampaignAdmin || userAccessType == ItineraryAccessType.EventAdmin; } } } /// <summary> /// Defines the possible access types that can potentially manage an <see cref="IAuthorizableTask"/> /// </summary> public enum TaskAccessType { Unknown = 0, Unauthorized = 1, SiteAdmin = 2, OrganizationAdmin = 3, CampaignAdmin = 4, EventAdmin = 5, } }
#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 XcodeBuilder { /// <summary> /// Class representing a PBXNativeTarget in an Xcode project /// </summary> sealed class Target : Object { /// <summary> /// Type of the product of the target /// </summary> public enum EProductType { NA, //!< Unknown StaticLibrary, //!< Static library Executable, //!< Executable DynamicLibrary, //!< Dylib ApplicationBundle, //!< Application bundle ObjFile, //!< Object file Utility //!< Utility } /// <summary> /// Create an instance. /// </summary> /// <param name="module">Module associated with</param> /// <param name="project">Project to add the Target to.</param> public Target( Bam.Core.Module module, Project project) : base(project, module.GetType().Name, "PBXNativeTarget", project.GUID) { this.Module = module; this.Type = EProductType.NA; var configList = new ConfigurationList(this); this.ConfigurationList = configList; project.AppendConfigurationList(configList); this.TargetDependencies = new Bam.Core.Array<TargetDependency>(); this.ProposedTargetDependencies = new Bam.Core.Array<Target>(); this.BuildPhases = new System.Lazy<Bam.Core.Array<BuildPhase>>(() => new Bam.Core.Array<BuildPhase>()); this.SourcesBuildPhase = new System.Lazy<SourcesBuildPhase>(() => { var phase = new SourcesBuildPhase(this); this.AppendBuildPhase(phase); this.Project.AppendSourcesBuildPhase(phase); return phase; }); this.FrameworksBuildPhase = new System.Lazy<XcodeBuilder.FrameworksBuildPhase>(() => { var phase = new FrameworksBuildPhase(this); this.Project.AppendFrameworksBuildPhase(phase); this.AppendBuildPhase(phase); return phase; }); this.PreBuildBuildPhase = new System.Lazy<ShellScriptBuildPhase>(() => { return new ShellScriptBuildPhase(this, "Pre Build", (target) => { var content = new System.Text.StringBuilder(); foreach (var config in target.ConfigurationList) { content.Append($"if [ \\\"$CONFIGURATION\\\" = \\\"{config.Name}\\\" ]; then\\n\\n"); config.SerializePreBuildCommands(content, 1); content.Append("fi\\n\\n"); } return content.ToString(); }); }); this.PostBuildBuildPhase = new System.Lazy<ShellScriptBuildPhase>(() => { return new ShellScriptBuildPhase(this, "Post Build", (target) => { var content = new System.Text.StringBuilder(); foreach (var config in target.ConfigurationList) { content.Append($"if [ \\\"$CONFIGURATION\\\" = \\\"{config.Name}\\\" ]; then\\n\\n"); config.SerializePostBuildCommands(content, 1); content.Append("fi\\n\\n"); } return content.ToString(); }); }); } /// <summary> /// Get the Module /// </summary> public Bam.Core.Module Module { get; private set; } // as value types cannot be used in lock statements, have a separate lock guard private static readonly object TypeGuard = new object(); private EProductType Type { get; set; } /// <summary> /// Get the ConfigurationList /// </summary> public ConfigurationList ConfigurationList { get; private set; } private FileReference FileReference = null; /// <summary> /// Get the FileReference to the Target. /// </summary> /// <returns></returns> public FileReference GetFileReference() { return this.FileReference; } /// <summary> /// Get the list of TargetDependencies /// </summary> public Bam.Core.Array<TargetDependency> TargetDependencies { get; private set; } private Bam.Core.Array<Target> ProposedTargetDependencies { get; set; } private System.Lazy<Bam.Core.Array<BuildPhase>> BuildPhases { get; set; } private void AppendBuildPhase( BuildPhase phase) { lock (this.BuildPhases) { this.BuildPhases.Value.Add(phase); } } /// <summary> /// Get the sources build phase /// </summary> public System.Lazy<SourcesBuildPhase> SourcesBuildPhase { get; private set; } private System.Lazy<FrameworksBuildPhase> FrameworksBuildPhase { get; set; } private System.Lazy<ShellScriptBuildPhase> PreBuildBuildPhase { get; set; } /// <summary> /// Get the shell script build phase /// </summary> public System.Lazy<ShellScriptBuildPhase> PostBuildBuildPhase { get; private set; } /// <summary> /// Set the type of the Target /// </summary> /// <param name="type"></param> public void SetType( EProductType type) { lock (TypeGuard) { if (this.Type == type) { return; } if (this.Type != EProductType.NA) { // exception: if there is a multi-config build, and collation modules have been executed on one configuration // prior to linking on another if (EProductType.Executable == type && this.Type == EProductType.ApplicationBundle) { return; } throw new Bam.Core.Exception( $"Product type has already been set to {this.Type.ToString()}. Cannot change it to {type.ToString()}" ); } this.Type = type; } } /// <summary> /// Is this a utility type Target? /// </summary> public bool IsUtilityType => this.Type == EProductType.Utility; /// <summary> /// Get the Configuration for the Target /// </summary> /// <param name="module">Associated module</param> /// <returns></returns> public Configuration GetConfiguration( Bam.Core.Module module) { lock (this.ConfigurationList) { var moduleConfig = module.BuildEnvironment.Configuration; var existingConfig = this.ConfigurationList.FirstOrDefault(item => item.Config == moduleConfig); if (null != existingConfig) { return existingConfig; } var config = this.EnsureTargetConfigurationExists(module, this.Project); return config; } } /// <summary> /// Ensure that the output file exists on the Target /// </summary> /// <param name="path">TokenizedString to the output file</param> /// <param name="type">Type of the file reference</param> /// <param name="productType">Product type of the Target</param> public void EnsureOutputFileReferenceExists( Bam.Core.TokenizedString path, FileReference.EFileType type, Target.EProductType productType) { this.SetType(productType); System.Threading.LazyInitializer.EnsureInitialized(ref this.FileReference, () => { var fileRef = this.Project.EnsureFileReferenceExists(path, type, sourceTree: FileReference.ESourceTree.BuiltProductsDir); this.Project.ProductRefGroup.AddChild(fileRef); return fileRef; }); } private BuildFile EnsureBuildFileExists( Bam.Core.TokenizedString path, FileReference.EFileType type, FileReference.ESourceTree? requestedSourceTree = null) { lock (this.Project) { var relativePath = this.Project.GetRelativePathToProject(path); FileReference.ESourceTree sourceTree; if (requestedSourceTree.HasValue) { sourceTree = requestedSourceTree.Value; } else { // guess if (null == relativePath) { sourceTree = FileReference.ESourceTree.Absolute; } else { sourceTree = FileReference.ESourceTree.SourceRoot; } } var fileRef = this.Project.EnsureFileReferenceExists( path, relativePath, type, sourceTree: sourceTree); var buildFile = this.Project.EnsureBuildFileExists(fileRef, this); return buildFile; } } private Group CreateGroupHierarchy( Bam.Core.TokenizedString path) { lock (this.Project) { var existingGroup = this.Project.GetGroupForPath(path); if (null != existingGroup) { return existingGroup; } var basenameTS = this.Module.CreateTokenizedString("@basename($(0))", path); lock (basenameTS) { if (!basenameTS.IsParsed) { basenameTS.Parse(); } } var basename = basenameTS.ToString(); var group = new Group(this, basename, path); this.Project.AppendGroup(group); this.Project.AssignGroupToPath(path, group); if (path.ToString().Contains(System.IO.Path.DirectorySeparatorChar)) { var parent = this.Module.CreateTokenizedString("@dir($(0))", path); lock (parent) { if (!parent.IsParsed) { parent.Parse(); } } var parentGroup = this.CreateGroupHierarchy(parent); parentGroup.AddChild(group); } return group; } } private void AddFileRefToGroup( FileReference fileRef) { var relDir = this.Module.CreateTokenizedString( "@isrelative(@trimstart(@relativeto(@dir($(0)),$(packagedir)),../),@dir($(0)))", fileRef.Path ); lock (relDir) { if (!relDir.IsParsed) { relDir.Parse(); } } if (relDir.ToString().Equals(".", System.StringComparison.Ordinal)) { // this can happen if the source file is directly in the package directory this.Project.MainGroup.AddChild(fileRef); } else { var newGroup = this.CreateGroupHierarchy(relDir); var parentGroup = newGroup; while (parentGroup.Parent != null) { parentGroup = parentGroup.Parent; if (parentGroup == this.Project.MainGroup) { break; } } this.Project.MainGroup.AddChild(parentGroup); newGroup.AddChild(fileRef); } } /// <summary> /// Ensure that a source build file exists on the Target /// </summary> /// <param name="path">TokenizedString for the build file</param> /// <param name="type">File type of the file reference</param> /// <returns>The Build File from the Target</returns> public BuildFile EnsureSourceBuildFileExists( Bam.Core.TokenizedString path, FileReference.EFileType type) { lock (this.SourcesBuildPhase) { var buildFile = this.EnsureBuildFileExists(path, type); this.AddFileRefToGroup(buildFile.FileRef); this.SourcesBuildPhase.Value.AddBuildFile(buildFile); return buildFile; } } /// <summary> /// Ensure that the Frameworks build file exists /// </summary> /// <param name="path">TokenizedString for the frameworks build file</param> /// <param name="type">File type of the file reference</param> /// <param name="sourceTree">Source tree</param> /// <returns>The BuildFile created</returns> public BuildFile EnsureFrameworksBuildFileExists( Bam.Core.TokenizedString path, FileReference.EFileType type, FileReference.ESourceTree sourceTree) { lock (this.FrameworksBuildPhase) { var buildFile = this.EnsureBuildFileExists(path, type, requestedSourceTree: sourceTree); this.FrameworksBuildPhase.Value.AddBuildFile(buildFile); this.Project.Frameworks.AddChild(buildFile.FileRef); return buildFile; } } /// <summary> /// Ensure that the header file exists on the Target. /// </summary> /// <param name="path">TokenizedString for the header</param> public void EnsureHeaderFileExists( Bam.Core.TokenizedString path) { var relativePath = this.Project.GetRelativePathToProject(path); this.EnsureFileOfTypeExists(path, FileReference.EFileType.HeaderFile, relativePath: relativePath); } /// <summary> /// Ensure that a file of the given type exists. /// </summary> /// <param name="path">TokenizedString for the file</param> /// <param name="type">Type of that file</param> /// <param name="relativePath">Relative path to use</param> /// <param name="explicitType">Should this use an explicit type?</param> public void EnsureFileOfTypeExists( Bam.Core.TokenizedString path, FileReference.EFileType type, string relativePath = null, bool explicitType = true) { var sourceTree = (relativePath != null) ? FileReference.ESourceTree.SourceRoot : FileReference.ESourceTree.Absolute; var fileRef = this.Project.EnsureFileReferenceExists( path, relativePath, type, explicitType: explicitType, sourceTree: sourceTree); this.AddFileRefToGroup(fileRef); } /// <summary> /// Add a dependency on another Target /// </summary> /// <param name="other">Target that is a dependency</param> public void DependsOn( Target other) { if (this.Project == other.Project) { var linkedBuildFile = this.Project.EnsureBuildFileExists(other.FileReference, this); this.FrameworksBuildPhase.Value.AddBuildFile(linkedBuildFile); } else { var fileRefAlias = other.FileReference.MakeLinkableAlias(this.Module, this.Project); var linkedBuildFile = this.Project.EnsureBuildFileExists(fileRefAlias, this); this.FrameworksBuildPhase.Value.AddBuildFile(linkedBuildFile); } } /// <summary> /// Add an order only dependency on another Target /// </summary> /// <param name="other">Target that is a dependency</param> public void Requires( Target other) { lock (this.ProposedTargetDependencies) { this.ProposedTargetDependencies.AddUnique(other); } } /// <summary> /// Resolve all target dependencies /// </summary> public void ResolveTargetDependencies() { foreach (var depTarget in this.ProposedTargetDependencies) { if (this.Project == depTarget.Project) { var nativeTargetItemProxy = this.Project.GetContainerItemProxy(depTarget, depTarget.Project); if (null == nativeTargetItemProxy) { nativeTargetItemProxy = new ContainerItemProxy(this.Project, depTarget); } // note that target dependencies can be shared in a project by many Targets // but each Target needs a reference to it var dependency = this.Project.GetTargetDependency(depTarget, nativeTargetItemProxy); if (null == dependency) { dependency = new TargetDependency(this.Project, depTarget, nativeTargetItemProxy); } this.TargetDependencies.AddUnique(dependency); } else { if (null == depTarget.FileReference) { // expect header libraries not to have a build output if (!(depTarget.Module is C.HeaderLibrary)) { Bam.Core.Log.ErrorMessage( $"Project {depTarget.Name} cannot be a target dependency as it has no output FileReference" ); } continue; } var relativePath = this.Project.GetRelativePathToProject(depTarget.Project.ProjectDir); var sourceTree = FileReference.ESourceTree.NA; if (null == relativePath) { sourceTree = FileReference.ESourceTree.Absolute; } else { sourceTree = FileReference.ESourceTree.Group; // note: not relative to SOURCE } var dependentProjectFileRef = this.Project.EnsureFileReferenceExists( depTarget.Project.ProjectDir, relativePath, FileReference.EFileType.Project, explicitType: false, sourceTree: sourceTree); this.Project.MainGroup.AddChild(dependentProjectFileRef); // need a ContainerItemProxy for the dependent NativeTarget // which is associated with a local PBXTargetDependency var nativeTargetItemProxy = this.Project.GetContainerItemProxy(depTarget, dependentProjectFileRef); if (null == nativeTargetItemProxy) { nativeTargetItemProxy = new ContainerItemProxy(this.Project, dependentProjectFileRef, depTarget); } // note that target dependencies can be shared in a project by many Targets // but each Target needs a reference to it var targetDependency = this.Project.GetTargetDependency(depTarget.Name, nativeTargetItemProxy); if (null == targetDependency) { // no 'target', but does have the name of the dependent targetDependency = new TargetDependency(this.Project, depTarget.Name, nativeTargetItemProxy); } this.TargetDependencies.AddUnique(targetDependency); // need a ContainerItemProxy for the filereference of the dependent NativeTarget // which is associated with a local PBXReferenceProxy var dependentFileRefItemProxy = this.Project.GetContainerItemProxy(depTarget.FileReference, dependentProjectFileRef); if (null == dependentFileRefItemProxy) { // note, uses the name of the Target, not the FileReference dependentFileRefItemProxy = new ContainerItemProxy(this.Project, dependentProjectFileRef, depTarget.FileReference, depTarget.Name); } var refProxy = this.Project.GetReferenceProxyForRemoteRef(dependentFileRefItemProxy); if (null == refProxy) { refProxy = new ReferenceProxy( this.Project, depTarget.FileReference.Type, depTarget.FileReference.Path, dependentFileRefItemProxy, depTarget.FileReference.SourceTree); } // TODO: all PBXReferenceProxies could go into the same group // but at the moment, a group is made for each var productRefGroup = this.Project.GroupWithChild(refProxy); if (null == productRefGroup) { productRefGroup = new Group(this.Project, "Products", refProxy); this.Project.AppendGroup(productRefGroup); } this.Project.EnsureProjectReferenceExists(productRefGroup, dependentProjectFileRef); } } } /// <summary> /// Add prebuild commands to the Target /// </summary> /// <param name="commands">List of commands</param> /// <param name="configuration">Configuration to add to</param> /// <param name="outputPaths">List of output paths</param> public void AddPreBuildCommands( Bam.Core.StringArray commands, Configuration configuration, Bam.Core.TokenizedStringArray outputPaths) { if (!this.PreBuildBuildPhase.IsValueCreated) { this.Project.AppendShellScriptsBuildPhase(this.PreBuildBuildPhase.Value); // do not add PreBuildBuildPhase to this.BuildPhases, so that it can be serialized in the right order } configuration.AppendPreBuildCommands(commands); if (null != outputPaths) { this.PreBuildBuildPhase.Value.AddOutputPaths(outputPaths); } } /// <summary> /// Add post build commands /// </summary> /// <param name="commands">Commands to add</param> /// <param name="configuration">Configuration to add to</param> public void AddPostBuildCommands( Bam.Core.StringArray commands, Configuration configuration) { if (!this.PostBuildBuildPhase.IsValueCreated) { this.Project.AppendShellScriptsBuildPhase(this.PostBuildBuildPhase.Value); // do not add PostBuildBuildPhase to this.BuildPhases, so that it can be serialized in the right order } configuration.AppendPostBuildCommands(commands); } /// <summary> /// Make this Target into an application bundle /// </summary> public void MakeApplicationBundle() { if (this.Type == EProductType.ApplicationBundle) { return; } if (this.Type != EProductType.Executable) { throw new Bam.Core.Exception("Can only change an executable to an application bundle"); } this.Type = EProductType.ApplicationBundle; this.FileReference.MakeApplicationBundle(); } private string ProductTypeToString() { switch (this.Type) { case EProductType.StaticLibrary: return "com.apple.product-type.library.static"; case EProductType.Executable: return "com.apple.product-type.tool"; case EProductType.DynamicLibrary: return "com.apple.product-type.library.dynamic"; case EProductType.ApplicationBundle: return "com.apple.product-type.application"; case EProductType.ObjFile: return "com.apple.product-type.objfile"; case EProductType.Utility: // this is analogous to the VisualStudio 'utility' project - nothing needs building, just pre/post build steps return "com.apple.product-type.library.static"; default: throw new Bam.Core.Exception( $"Unrecognized product type, {this.Type.ToString()}, for module {this.Module.ToString()}" ); } } /// <summary> /// Serialize the Target /// </summary> /// <param name="text">StringBuilder to write to</param> /// <param name="indentLevel">Number of tabs to indent by.</param> public override void Serialize( System.Text.StringBuilder text, int indentLevel) { var indent = new string('\t', indentLevel); var indent2 = new string('\t', indentLevel + 1); var indent3 = new string('\t', indentLevel + 2); text.AppendLine($"{indent}{this.GUID} /* {this.Name} */ = {{"); text.AppendLine($"{indent2}isa = {this.IsA};"); text.AppendLine($"{indent2}buildConfigurationList = {this.ConfigurationList.GUID} /* Build configuration list for {this.ConfigurationList.Parent.IsA} \"{this.ConfigurationList.Parent.Name}\" */;"); if (this.BuildPhases.IsValueCreated || this.PreBuildBuildPhase.IsValueCreated || (null != this.PostBuildBuildPhase)) { // make sure that pre-build phases appear first // then any regular build phases // and then post-build phases. // any of these can be missing text.AppendLine($"{indent2}buildPhases = ("); void dumpPhase( BuildPhase phase) { text.AppendLine($"{indent3}{phase.GUID} /* {phase.Name} */,"); } if (this.PreBuildBuildPhase.IsValueCreated) { dumpPhase(this.PreBuildBuildPhase.Value); } if (this.BuildPhases.IsValueCreated) { foreach (var phase in this.BuildPhases.Value) { dumpPhase(phase); } } if (this.PostBuildBuildPhase.IsValueCreated) { dumpPhase(this.PostBuildBuildPhase.Value); } text.AppendLine($"{indent2});"); } text.AppendLine($"{indent2}buildRules = ("); text.AppendLine($"{indent2});"); text.AppendLine($"{indent2}dependencies = ("); foreach (var dependency in this.TargetDependencies) { text.AppendLine($"{indent3}{dependency.GUID} /* {dependency.Name} */,"); } text.AppendLine($"{indent2});"); text.AppendLine($"{indent2}name = {this.Name};"); text.AppendLine($"{indent2}productName = {this.Name};"); if (null != this.FileReference) { text.AppendLine($"{indent2}productReference = {this.FileReference.GUID} /* {this.FileReference.Name} */;"); } text.AppendLine($"{indent2}productType = \"{this.ProductTypeToString()}\";"); text.AppendLine($"{indent}}};"); } private Configuration EnsureTargetConfigurationExists( Bam.Core.Module module, Project project) { var configList = this.ConfigurationList; lock (configList) { var config = module.BuildEnvironment.Configuration; var existingConfig = configList.FirstOrDefault(item => item.Config == config); if (null != existingConfig) { return existingConfig; } // if a new target config is needed, then a new project config is needed too project.EnsureProjectConfigurationExists(module); var newConfig = new Configuration(module.BuildEnvironment.Configuration, project, this); project.AppendAllConfigurations(newConfig); configList.AddConfiguration(newConfig); try { var clangMeta = Bam.Core.Graph.Instance.PackageMetaData<Clang.MetaData>("Clang"); // set which SDK to build against newConfig["SDKROOT"] = new UniqueConfigurationValue(clangMeta.SDK); // set the minimum version of macOS/iOS to run against newConfig["MACOSX_DEPLOYMENT_TARGET"] = new UniqueConfigurationValue(clangMeta.MacOSXMinimumVersionSupported); } catch (System.Collections.Generic.KeyNotFoundException) { if (Bam.Core.OSUtilities.IsOSXHosting) { // try a forced discovery, since it doesn't appear to have happened prior to now // which suggests a project with no source files var clangMeta = Bam.Core.Graph.Instance.PackageMetaData<Clang.MetaData>("Clang"); (clangMeta as C.IToolchainDiscovery).Discover(C.EBit.SixtyFour); // arbitrary // set which SDK to build against newConfig["SDKROOT"] = new UniqueConfigurationValue(clangMeta.SDK); // set the minimum version of macOS/iOS to run against newConfig["MACOSX_DEPLOYMENT_TARGET"] = new UniqueConfigurationValue(clangMeta.MacOSXMinimumVersionSupported); } else { // arbitrary choice as we're not on macOS to look for valid SDK versions var sdk_version = "10.13"; newConfig["SDKROOT"] = new UniqueConfigurationValue("macosx" + sdk_version); newConfig["MACOSX_DEPLOYMENT_TARGET"] = new UniqueConfigurationValue(sdk_version); } } return newConfig; } } } }
// 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.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; namespace System.Xml { // // XmlCharCheckingWriter // internal partial class XmlCharCheckingWriter : XmlWrappingWriter { // // Fields // private bool _checkValues; private bool _checkNames; private bool _replaceNewLines; private string _newLineChars; private XmlCharType _xmlCharType; // // Constructor // internal XmlCharCheckingWriter(XmlWriter baseWriter, bool checkValues, bool checkNames, bool replaceNewLines, string newLineChars) : base(baseWriter) { Debug.Assert(checkValues || replaceNewLines); _checkValues = checkValues; _checkNames = checkNames; _replaceNewLines = replaceNewLines; _newLineChars = newLineChars; if (checkValues) { _xmlCharType = XmlCharType.Instance; } } // // XmlWriter implementation // public override XmlWriterSettings Settings { get { XmlWriterSettings s = base.writer.Settings; s = (s != null) ? (XmlWriterSettings)s.Clone() : new XmlWriterSettings(); if (_checkValues) { s.CheckCharacters = true; } if (_replaceNewLines) { s.NewLineHandling = NewLineHandling.Replace; s.NewLineChars = _newLineChars; } s.ReadOnly = true; return s; } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (_checkNames) { ValidateQName(name); } if (_checkValues) { if (pubid != null) { int i; if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw XmlConvert.CreateInvalidCharException(pubid, i); } } if (sysid != null) { CheckCharacters(sysid); } if (subset != null) { CheckCharacters(subset); } } if (_replaceNewLines) { sysid = ReplaceNewLines(sysid); pubid = ReplaceNewLines(pubid); subset = ReplaceNewLines(subset); } writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteStartElement(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } writer.WriteStartElement(prefix, localName, ns); } public override void WriteStartAttribute(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteCData(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines) { text = ReplaceNewLines(text); } int i; while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0) { writer.WriteCData(text.Substring(0, i + 2)); text = text.Substring(i + 2); } } writer.WriteCData(text); } public override void WriteComment(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '-', '-'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } writer.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { if (_checkNames) { ValidateNCName(name); } if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '?', '>'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } writer.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { if (_checkNames) { ValidateQName(name); } writer.WriteEntityRef(name); } public override void WriteWhitespace(string ws) { if (ws == null) { ws = string.Empty; } // "checkNames" is intentional here; if false, the whitespaces are checked in XmlWellformedWriter if (_checkNames) { int i; if ((i = _xmlCharType.IsOnlyWhitespaceWithPos(ws)) != -1) { throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i))); } } if (_replaceNewLines) { ws = ReplaceNewLines(ws); } writer.WriteWhitespace(ws); } public override void WriteString(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines && WriteState != WriteState.Attribute) { text = ReplaceNewLines(text); } } writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } if (_checkValues) { CheckCharacters(buffer, index, count); } if (_replaceNewLines && WriteState != WriteState.Attribute) { string text = ReplaceNewLines(buffer, index, count); if (text != null) { WriteString(text); return; } } writer.WriteChars(buffer, index, count); } public override void WriteNmToken(string name) { if (_checkNames) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyNMTOKEN(name); } writer.WriteNmToken(name); } public override void WriteName(string name) { if (_checkNames) { XmlConvert.VerifyQName(name, ExceptionType.XmlException); } writer.WriteName(name); } public override void WriteQualifiedName(string localName, string ns) { if (_checkNames) { ValidateNCName(localName); } writer.WriteQualifiedName(localName, ns); } // // Private methods // private void CheckCharacters(string str) { XmlConvert.VerifyCharData(str, ExceptionType.ArgumentException); } private void CheckCharacters(char[] data, int offset, int len) { XmlConvert.VerifyCharData(data, offset, len, ExceptionType.ArgumentException); } private void ValidateNCName(string ncname) { if (ncname.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int len = ValidateNames.ParseNCName(ncname, 0); if (len != ncname.Length) { throw new ArgumentException(SR.Format(len == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(ncname, len))); } } private void ValidateQName(string name) { if (name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int colonPos; int len = ValidateNames.ParseQName(name, 0, out colonPos); if (len != name.Length) { string res = (len == 0 || (colonPos > -1 && len == colonPos + 1)) ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar; throw new ArgumentException(SR.Format(res, XmlException.BuildCharExceptionArgs(name, len))); } } private string ReplaceNewLines(string str) { if (str == null) { return null; } StringBuilder sb = null; int start = 0; int i; for (i = 0; i < str.Length; i++) { char ch; if ((ch = str[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); } else if (ch == '\r') { if (i + 1 < str.Length && str[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return str; } else { sb.Append(str, start, i - start); return sb.ToString(); } } private string ReplaceNewLines(char[] data, int offset, int len) { if (data == null) { return null; } StringBuilder sb = null; int start = offset; int endPos = offset + len; int i; for (i = offset; i < endPos; i++) { char ch; if ((ch = data[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } else if (ch == '\r') { if (i + 1 < endPos && data[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return null; } else { sb.Append(data, start, i - start); return sb.ToString(); } } // Interleave 2 adjacent invalid chars with a space. This is used for fixing invalid values of comments and PIs. // Any "--" in comment must be replaced with "- -" and any "-" at the end must be appended with " ". // Any "?>" in PI value must be replaced with "? >". private string InterleaveInvalidChars(string text, char invChar1, char invChar2) { StringBuilder sb = null; int start = 0; int i; for (i = 0; i < text.Length; i++) { if (text[i] != invChar2) { continue; } if (i > 0 && text[i - 1] == invChar1) { if (sb == null) { sb = new StringBuilder(text.Length + 5); } sb.Append(text, start, i - start); sb.Append(' '); start = i; } } // check last char & return if (sb == null) { return (i == 0 || text[i - 1] != invChar1) ? text : (text + ' '); } else { sb.Append(text, start, i - start); if (i > 0 && text[i - 1] == invChar1) { sb.Append(' '); } return sb.ToString(); } } } }
using Foo; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace Models.NorthwindIB.CF { public class NorthwindIBContext_CF : DbContext { public DbContextOptions<NorthwindIBContext_CF> Options { get; private set; } public NorthwindIBContext_CF(DbContextOptions<NorthwindIBContext_CF> options) : base(options) { // Hang onto it so that we can create a clone. Options = options; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Comment>() .HasKey(c => new { c.CreatedOn, c.SeqNum }); modelBuilder.Entity<OrderDetail>() .HasKey(od => new { od.OrderID, od.ProductID }); modelBuilder.Entity<OrderDetail>().Property(od => od.OrderID).ValueGeneratedNever(); modelBuilder.Entity<Supplier>() .OwnsOne<Location>(s => s.Location); } #region DbSets public DbSet<Category> Categories { get; set; } public DbSet<Customer> Customers { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<EmployeeTerritory> EmployeeTerritories { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<PreviousEmployee> PreviousEmployees { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<Supplier> Suppliers { get; set; } public DbSet<Territory> Territories { get; set; } public DbSet<User> Users { get; set; } public DbSet<UserRole> UserRoles { get; set; } public DbSet<InternationalOrder> InternationalOrders { get; set; } public DbSet<TimeLimit> TimeLimits { get; set; } public DbSet<TimeGroup> TimeGroups { get; set; } public DbSet<Comment> Comments { get; set; } // public DbSet<Geospatial> Geospatials { get; set; } public DbSet<UnusualDate> UnusualDates { get; set; } #endregion EntityQueries } } namespace Foo { [AttributeUsage(AttributeTargets.Class)] // NEW public class CustomerValidator : ValidationAttribute { public override Boolean IsValid(Object value) { var cust = value as Customer; if (cust != null && cust.CompanyName.ToLower() == "error") { ErrorMessage = "This customer is not valid!"; return false; } return true; } } [AttributeUsage(AttributeTargets.Property)] public class CustomValidator : ValidationAttribute { public override Boolean IsValid(Object value) { try { string val = (string)value; if (!string.IsNullOrEmpty(val) && val.StartsWith("Error")) { ErrorMessage = "{0} equals the word 'Error'"; return false; } return true; } catch (Exception e) { var x = e; return false; } } } #region Category class [Table("Category", Schema = "dbo")] public partial class Category { #region Data Properties /// <summary>Gets or sets the CategoryID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("CategoryID")] public int CategoryID { get; set; } /// <summary>Gets or sets the CategoryName. </summary> [Column("CategoryName")] public string CategoryName { get; set; } /// <summary>Gets or sets the Description. </summary> [Column("Description")] public string Description { get; set; } /// <summary>Gets or sets the Picture. </summary> [Column("Picture")] public byte[] Picture { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] [DefaultValue(2)] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Products. </summary> // [DataMember] [InverseProperty("Category")] public ICollection<Product> Products { get; set; } #endregion Navigation properties } #endregion Category class #region Customer class [Table("Customer", Schema = "dbo")] [CustomerValidator] public partial class Customer { #region Data Properties /// <summary>Gets or sets the CustomerID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("CustomerID")] public System.Guid CustomerID { get; set; } /// <summary>Gets or sets the CustomerID_OLD. </summary> [Column("CustomerID_OLD")] [MaxLength(5)] public string CustomerID_OLD { get; set; } /// <summary>Gets or sets the CompanyName. </summary> [Column("CompanyName")] [MaxLength(40)] [Required] public string CompanyName { get; set; } /// <summary>Gets or sets the ContactName. </summary> [Column("ContactName")] [CustomValidator] [MaxLength(30)] public string ContactName { get; set; } /// <summary>Gets or sets the ContactTitle. </summary> [Column("ContactTitle")] [MaxLength(30)] public string ContactTitle { get; set; } /// <summary>Gets or sets the Address. </summary> [Column("Address")] [MaxLength(60)] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> [Column("City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> [Column("Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> [Column("PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> [Column("Country")] [MaxLength(15)] public string Country { get; set; } /// <summary>Gets or sets the Phone. </summary> [Column("Phone")] [MaxLength(24)] public string Phone { get; set; } /// <summary>Gets or sets the Fax. </summary> [Column("Fax")] [MaxLength(24)] public string Fax { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] [ConcurrencyCheck] public System.Nullable<int> RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Orders. </summary> [InverseProperty("Customer")] public ICollection<Order> Orders { get; set; } #endregion Navigation properties } #endregion Customer class #region Employee class [Table("Employee", Schema = "dbo")] public partial class Employee { #region Data Properties /// <summary>Gets or sets the EmployeeID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the LastName. </summary> [Column("LastName")] [MaxLength(30)] [Required] public string LastName { get; set; } [Column("FirstName")] [MaxLength(30)] [Required] public string FirstName { get; set; } [Column("Title")] [MaxLength(30)] public string Title { get; set; } [Column("TitleOfCourtesy")] [MaxLength(25)] public string TitleOfCourtesy { get; set; } [Column("BirthDate")] public System.Nullable<System.DateTime> BirthDate { get; set; } [Column("HireDate")] public System.Nullable<System.DateTime> HireDate { get; set; } [Column("Address")] [MaxLength(60)] public string Address { get; set; } [Column("City")] [MaxLength(15)] public string City { get; set; } [Column("Region")] [MaxLength(15)] public string Region { get; set; } [Column("PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } [Column("Country")] [MaxLength(15)] public string Country { get; set; } [Column("HomePhone")] [MaxLength(24)] public string HomePhone { get; set; } [Column("Extension")] [MaxLength(4)] public string Extension { get; set; } [Column("Photo")] public byte[] Photo { get; set; } [Column("Notes")] public string Notes { get; set; } [Column("PhotoPath")] [MaxLength(255)] public string PhotoPath { get; set; } [Column("ReportsToEmployeeID")] public System.Nullable<int> ReportsToEmployeeID { get; set; } [Column("RowVersion")] public int RowVersion { get; set; } [Column("FullName")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public String FullName { get; set; } #endregion Data Properties #region Navigation properties [InverseProperty("Manager")] public ICollection<Employee> DirectReports { get; set; } [ForeignKey("ReportsToEmployeeID")] [InverseProperty("DirectReports")] public Employee Manager { get; set; } [InverseProperty("Employee")] public ICollection<EmployeeTerritory> EmployeeTerritories { get; set; } [InverseProperty("Employee")] public ICollection<Order> Orders { get; set; } //[InverseProperty("Employees")] //public ICollection<Territory> Territories { get; set; } #endregion Navigation properties } #endregion Employee class #region EmployeeTerritory class [Table("EmployeeTerritory", Schema = "dbo")] public partial class EmployeeTerritory { #region Data Properties /// <summary>Gets or sets the ID. </summary> [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_ID")] public int ID { get; set; } /// <summary>Gets or sets the EmployeeID. </summary> // [DataMember] //[ForeignKey("Employee")] [Column("EmployeeID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the TerritoryID. </summary> // [DataMember] // [ForeignKey("Territory")] [Column("TerritoryID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_TerritoryID")] public int TerritoryID { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Employee. </summary> // [DataMember] [ForeignKey("EmployeeID")] [InverseProperty("EmployeeTerritories")] public Employee Employee { get; set; } /// <summary>Gets or sets the Territory. </summary> // [DataMember] [ForeignKey("TerritoryID")] [InverseProperty("EmployeeTerritories")] public Territory Territory { get; set; } #endregion Navigation properties } #endregion EmployeeTerritory class #region Order class [Table("Order", Schema = "dbo")] public partial class Order { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the CustomerID. </summary> // [DataMember] // [ForeignKey("Customer")] [Column("CustomerID")] public System.Nullable<System.Guid> CustomerID { get; set; } /// <summary>Gets or sets the EmployeeID. </summary> // [DataMember] // [ForeignKey("Employee")] [Column("EmployeeID")] public System.Nullable<int> EmployeeID { get; set; } /// <summary>Gets or sets the OrderDate. </summary> // [DataMember] [Column("OrderDate")] public System.Nullable<System.DateTime> OrderDate { get; set; } /// <summary>Gets or sets the RequiredDate. </summary> // [DataMember] [Column("RequiredDate")] public System.Nullable<System.DateTime> RequiredDate { get; set; } /// <summary>Gets or sets the ShippedDate. </summary> // [DataMember] [Column("ShippedDate")] public System.Nullable<System.DateTime> ShippedDate { get; set; } /// <summary>Gets or sets the Freight. </summary> // [DataMember] [Column("Freight")] public System.Nullable<decimal> Freight { get; set; } /// <summary>Gets or sets the ShipName. </summary> // [DataMember] [Column("ShipName")] // [IbVal.StringLengthVerifier(MaxValue=40, IsRequired=false, ErrorMessageResourceName="Order_ShipName")] [MaxLength(40)] public string ShipName { get; set; } /// <summary>Gets or sets the ShipAddress. </summary> // [DataMember] [Column("ShipAddress")] // [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="Order_ShipAddress")] [MaxLength(60)] public string ShipAddress { get; set; } /// <summary>Gets or sets the ShipCity. </summary> // [DataMember] [Column("ShipCity")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipCity")] [MaxLength(15)] public string ShipCity { get; set; } /// <summary>Gets or sets the ShipRegion. </summary> // [DataMember] [Column("ShipRegion")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipRegion")] [MaxLength(15)] public string ShipRegion { get; set; } /// <summary>Gets or sets the ShipPostalCode. </summary> // [DataMember] [Column("ShipPostalCode")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="Order_ShipPostalCode")] [MaxLength(10)] public string ShipPostalCode { get; set; } /// <summary>Gets or sets the ShipCountry. </summary> // [DataMember] [Column("ShipCountry")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipCountry")] [MaxLength(15)] public string ShipCountry { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Order_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Customer. </summary> // [DataMember] [ForeignKey("CustomerID")] [InverseProperty("Orders")] public Customer Customer { get; set; } /// <summary>Gets or sets the Employee. </summary> // [DataMember] [ForeignKey("EmployeeID")] [InverseProperty("Orders")] public Employee Employee { get; set; } /// <summary>Gets the OrderDetails. </summary> // [DataMember] [InverseProperty("Order")] public ICollection<OrderDetail> OrderDetails { get; set; } /// <summary>Gets or sets the InternationalOrder. </summary> // [DataMember] [InverseProperty("Order")] public InternationalOrder InternationalOrder { get; set; } #endregion Navigation properties } #endregion Order class #region OrderDetail class [Table("OrderDetail", Schema = "dbo")] public partial class OrderDetail { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> // [Key] // [DatabaseGenerated(DatabaseGeneratedOption.None)] // // [DataMember] [Column("OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the ProductID. </summary> // [Key] // [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("ProductID")] // // [DataMember] public int ProductID { get; set; } /// <summary>Gets or sets the UnitPrice. </summary> [Column("UnitPrice")] // // [DataMember] public decimal UnitPrice { get; set; } /// <summary>Gets or sets the Quantity. </summary> [Column("Quantity")] // // [DataMember] public short Quantity { get; set; } /// <summary>Gets or sets the Discount. </summary> [Column("Discount")] // // [DataMember] public float Discount { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] // // [DataMember] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Order. </summary> // // [DataMember] [ForeignKey("OrderID")] [InverseProperty("OrderDetails")] public Order Order { get; set; } /// <summary>Gets or sets the Product. </summary> [ForeignKey("ProductID")] // [InverseProperty("OrderDetails")] // // [DataMember] public Product Product { get; set; } #endregion Navigation properties } #endregion OrderDetail class #region PreviousEmployee class [Table("PreviousEmployee", Schema = "dbo")] public partial class PreviousEmployee { #region Data Properties /// <summary>Gets or sets the EmployeeID. </summary> [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("EmployeeID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="PreviousEmployee_EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the LastName. </summary> // [DataMember] [Column("LastName")] // [IbVal.StringLengthVerifier(MaxValue=20, IsRequired=true, ErrorMessageResourceName="PreviousEmployee_LastName")] [MaxLength(20)] [Required] public string LastName { get; set; } /// <summary>Gets or sets the FirstName. </summary> // [DataMember] [Column("FirstName")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=true, ErrorMessageResourceName="PreviousEmployee_FirstName")] [MaxLength(10)] [Required] public string FirstName { get; set; } /// <summary>Gets or sets the Title. </summary> // [DataMember] [Column("Title")] // [IbVal.StringLengthVerifier(MaxValue=30, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Title")] [MaxLength(30)] public string Title { get; set; } /// <summary>Gets or sets the TitleOfCourtesy. </summary> // [DataMember] [Column("TitleOfCourtesy")] // [IbVal.StringLengthVerifier(MaxValue=25, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_TitleOfCourtesy")] [MaxLength(25)] public string TitleOfCourtesy { get; set; } /// <summary>Gets or sets the BirthDate. </summary> // [DataMember] [Column("BirthDate")] public System.Nullable<System.DateTime> BirthDate { get; set; } /// <summary>Gets or sets the HireDate. </summary> // [DataMember] [Column("HireDate")] public System.Nullable<System.DateTime> HireDate { get; set; } /// <summary>Gets or sets the Address. </summary> // [DataMember] [Column("Address")] // [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Address")] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> // [DataMember] [Column("City")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> // [DataMember] [Column("Region")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> // [DataMember] [Column("PostalCode")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> // [DataMember] [Column("Country")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Country")] [MaxLength(15)] public string Country { get; set; } /// <summary>Gets or sets the HomePhone. </summary> // [DataMember] [Column("HomePhone")] // [IbVal.StringLengthVerifier(MaxValue=24, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_HomePhone")] [MaxLength(24)] public string HomePhone { get; set; } /// <summary>Gets or sets the Extension. </summary> // [DataMember] [Column("Extension")] // [IbVal.StringLengthVerifier(MaxValue=4, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Extension")] [MaxLength(4)] public string Extension { get; set; } /// <summary>Gets or sets the Photo. </summary> // [DataMember] [Column("Photo")] public byte[] Photo { get; set; } /// <summary>Gets or sets the Notes. </summary> // [DataMember] [Column("Notes")] public string Notes { get; set; } /// <summary>Gets or sets the PhotoPath. </summary> // [DataMember] [Column("PhotoPath")] // [IbVal.StringLengthVerifier(MaxValue=255, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_PhotoPath")] [MaxLength(255)] public string PhotoPath { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="PreviousEmployee_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties #endregion Navigation properties } #endregion PreviousEmployee class #region Product class [Table("Product", Schema = "dbo")] public partial class Product { #region Data Properties /// <summary>Gets or sets the ProductID. </summary> [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ProductID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_ProductID")] public int ProductID { get; set; } /// <summary>Gets or sets the ProductName. </summary> // [DataMember] [Column("ProductName")] // [IbVal.StringLengthVerifier(MaxValue=40, IsRequired=true, ErrorMessageResourceName="Product_ProductName")] [MaxLength(40)] public string ProductName { get; set; } /// <summary>Gets or sets the SupplierID. </summary> // [DataMember] //[ForeignKey("Supplier")] [Column("SupplierID")] public System.Nullable<int> SupplierID { get; set; } /// <summary>Gets or sets the CategoryID. </summary> // [DataMember] // [ForeignKey("Category")] [Column("CategoryID")] public System.Nullable<int> CategoryID { get; set; } /// <summary>Gets or sets the QuantityPerUnit. </summary> // [DataMember] [Column("QuantityPerUnit")] // [IbVal.StringLengthVerifier(MaxValue=20, IsRequired=false, ErrorMessageResourceName="Product_QuantityPerUnit")] public string QuantityPerUnit { get; set; } /// <summary>Gets or sets the UnitPrice. </summary> // [DataMember] [Column("UnitPrice")] public System.Nullable<decimal> UnitPrice { get; set; } /// <summary>Gets or sets the UnitsInStock. </summary> // [DataMember] [Column("UnitsInStock")] public System.Nullable<short> UnitsInStock { get; set; } /// <summary>Gets or sets the UnitsOnOrder. </summary> // [DataMember] [Column("UnitsOnOrder")] public System.Nullable<short> UnitsOnOrder { get; set; } /// <summary>Gets or sets the ReorderLevel. </summary> // [DataMember] [Column("ReorderLevel")] public System.Nullable<short> ReorderLevel { get; set; } /// <summary>Gets or sets the Discontinued. </summary> // [DataMember] [Column("Discontinued")] [DefaultValue(false)] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_Discontinued")] public bool Discontinued { get; set; } /// <summary>Gets or sets the DiscontinuedDate. </summary> // [DataMember] [Column("DiscontinuedDate")] public System.Nullable<System.DateTime> DiscontinuedDate { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Category. </summary> // [DataMember] [ForeignKey("CategoryID")] [InverseProperty("Products")] public Category Category { get; set; } ///// <summary>Gets the OrderDetails. </summary> //// [DataMember] //[InverseProperty("Product")] //public ICollection<OrderDetail> OrderDetails { // get; // set; //} /// <summary>Gets or sets the Supplier. </summary> // [DataMember] [ForeignKey("SupplierID")] [InverseProperty("Products")] public Supplier Supplier { get; set; } #endregion Navigation properties } #endregion Product class #region Region class [Table("Region", Schema = "dbo")] public partial class Region { #region Data Properties /// <summary>Gets or sets the RegionID. </summary> [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("RegionID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Region_RegionID")] public int RegionID { get; set; } /// <summary>Gets or sets the RegionDescription. </summary> // [DataMember] [Column("RegionDescription")] [MaxLength(50)] [Required] // [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Region_RegionDescription")] public string RegionDescription { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Region_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Territories. </summary> // [DataMember] [InverseProperty("Region")] public ICollection<Territory> Territories { get; set; } #endregion Navigation properties } #endregion Region class #region Role class [Table("Role", Schema = "dbo")] public partial class Role { #region Data Properties /// <summary>Gets or sets the Id. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public long Id { get; set; } /// <summary>Gets or sets the Name. </summary> [Column("Name")] [MaxLength(50)] [Required] public string Name { get; set; } /// <summary>Gets or sets the Description. </summary> [Column("Description")] [MaxLength(2000)] public string Description { get; set; } [Column("Ts")] // [Required] [Timestamp] public byte[] Ts { get; set; } [Column("RoleType")] public Nullable<Models.NorthwindIB.RoleType> RoleType { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the UserRoles. </summary> [InverseProperty("Role")] public ICollection<UserRole> UserRoles { get; set; } #endregion Navigation properties } #endregion Role class #region Supplier class [Table("Supplier", Schema = "dbo")] public partial class Supplier { #region Data Properties /// <summary>Gets or sets the SupplierID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("SupplierID")] public int SupplierID { get; set; } /// <summary>Gets or sets the CompanyName. </summary> [Column("CompanyName")] [MaxLength(40)] [Required] public string CompanyName { get; set; } /// <summary>Gets or sets the ContactName. </summary> [Column("ContactName")] [MaxLength(30)] public string ContactName { get; set; } /// <summary>Gets or sets the ContactTitle. </summary> [Column("ContactTitle")] [MaxLength(30)] public string ContactTitle { get; set; } // [DataMember] public Location Location { get; set; } ///// <summary>Gets or sets the Address. </summary> //// [DataMember] //[Column("Address")] //// [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="Supplier_Address")] //[MaxLength(60)] //public string Address { // get; // set; //} ///// <summary>Gets or sets the City. </summary> //// [DataMember] //[Column("City")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_City")] //[MaxLength(15)] //public string City { // get; // set; //} ///// <summary>Gets or sets the Region. </summary> //// [DataMember] //[Column("Region")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Region")] //[MaxLength(15)] //public string Region { // get; // set; //} ///// <summary>Gets or sets the PostalCode. </summary> //// [DataMember] //[Column("PostalCode")] //// [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="Supplier_PostalCode")] //[MaxLength(10)] //public string PostalCode { // get; // set; //} ///// <summary>Gets or sets the Country. </summary> //// [DataMember] //[Column("Country")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Country")] //[MaxLength(15)] //public string Country { // get; // set; //} /// <summary>Gets or sets the Phone. </summary> [Column("Phone")] [MaxLength(24)] public string Phone { get; set; } /// <summary>Gets or sets the Fax. </summary> [Column("Fax")] [MaxLength(24)] public string Fax { get; set; } /// <summary>Gets or sets the HomePage. </summary> [Column("HomePage")] public string HomePage { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Products. </summary> // [DataMember] [InverseProperty("Supplier")] public ICollection<Product> Products { get; set; } #endregion Navigation properties } #endregion Supplier class #region Location class public partial class Location { /// <summary>Gets or sets the Address. </summary> [Column("Address")] [MaxLength(60)] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> [Column("City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> // [DataMember] [Column("Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> [Column("PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> [Column("Country")] [MaxLength(15)] public string Country { get; set; } } #endregion Location #region Territory class [Table("Territory", Schema = "dbo")] public partial class Territory { #region Data Properties /// <summary>Gets or sets the TerritoryID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("TerritoryID")] public int TerritoryID { get; set; } /// <summary>Gets or sets the TerritoryDescription. </summary> [Column("TerritoryDescription")] [MaxLength(50)] [Required] public string TerritoryDescription { get; set; } /// <summary>Gets or sets the RegionID. </summary> // [ForeignKey("Region")] [Column("RegionID")] public int RegionID { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the EmployeeTerritories. </summary> [InverseProperty("Territory")] public ICollection<EmployeeTerritory> EmployeeTerritories { get; set; } /// <summary>Gets or sets the Region. </summary> [ForeignKey("RegionID")] [InverseProperty("Territories")] public Region Region { get; set; } #endregion Navigation properties } #endregion Territory class #region User class [Table("User", Schema = "dbo")] public partial class User { #region Data Properties /// <summary>Gets or sets the Id. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public long Id { get; set; } /// <summary>Gets or sets the UserName. </summary> [Column("UserName")] [MaxLength(100)] public string UserName { get; set; } /// <summary>Gets or sets the UserPassword. </summary> [Column("UserPassword")] [MaxLength(200)] public string UserPassword { get; set; } /// <summary>Gets or sets the FirstName. </summary> [Column("FirstName")] [MaxLength(100)] public string FirstName { get; set; } /// <summary>Gets or sets the LastName. </summary> [Column("LastName")] [MaxLength(100)] public string LastName { get; set; } /// <summary>Gets or sets the Email. </summary> [Column("Email")] [MaxLength(100)] public string Email { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [Column("RowVersion")] [ConcurrencyCheck] public decimal RowVersion { get; set; } /// <summary>Gets or sets the CreatedBy. </summary> [Column("CreatedBy")] [MaxLength(100)] public string CreatedBy { get; set; } /// <summary>Gets or sets the CreatedByUserId. </summary> [Column("CreatedByUserId")] public long CreatedByUserId { get; set; } /// <summary>Gets or sets the CreatedDate. </summary> [Column("CreatedDate")] public System.DateTime CreatedDate { get; set; } /// <summary>Gets or sets the ModifiedBy. </summary> [Column("ModifiedBy")] [MaxLength(100)] public string ModifiedBy { get; set; } /// <summary>Gets or sets the ModifiedByUserId. </summary> [Column("ModifiedByUserId")] public long ModifiedByUserId { get; set; } /// <summary>Gets or sets the ModifiedDate. </summary> [Column("ModifiedDate")] public System.DateTime ModifiedDate { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the UserRoles. </summary> [InverseProperty("User")] public ICollection<UserRole> UserRoles { get; set; } #endregion Navigation properties } #endregion User class #region UserRole class [Table("UserRole", Schema = "dbo")] public partial class UserRole { #region Data Properties /// <summary>Gets or sets the ID. </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ID")] public long ID { get; set; } /// <summary>Gets or sets the UserId. </summary> // [ForeignKey("User")] [Column("UserId")] public long UserId { get; set; } /// <summary>Gets or sets the RoleId. </summary> // [ForeignKey("Role")] [Column("RoleId")] public long RoleId { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Role. </summary> [ForeignKey("RoleId")] [InverseProperty("UserRoles")] public Role Role { get; set; } /// <summary>Gets or sets the User. </summary> [ForeignKey("UserId")] [InverseProperty("UserRoles")] public User User { get; set; } #endregion Navigation properties } #endregion UserRole class #region InternationalOrder class [Table("InternationalOrder", Schema = "dbo")] public partial class InternationalOrder { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> [Key] // [DataMember] [ForeignKey("Order")] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the CustomsDescription. </summary> // [DataMember] [Column("CustomsDescription")] [MaxLength(100)] public string CustomsDescription { get; set; } /// <summary>Gets or sets the ExciseTax. </summary> // [DataMember] [Column("ExciseTax")] public decimal ExciseTax { get; set; } /// <summary>Gets or sets the RowVersion. </summary> // [DataMember] [Column("RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Order. </summary> // [DataMember] //[ForeignKey("OrderID")] //[InverseProperty("InternationalOrder")] //[Required] public Order Order { get; set; } #endregion Navigation properties } #endregion InternationalOrder class #region TimeLimit class [Table("TimeLimit", Schema = "dbo")] public partial class TimeLimit { #region Data Properties [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } [Column("MaxTime")] [DefaultValue(0)] public System.TimeSpan MaxTime { get; set; } [Column("MinTime")] public Nullable<System.TimeSpan> MinTime { get; set; } // [ForeignKey("TimeGroup")] [Column("TimeGroupId")] public System.Nullable<int> TimeGroupId { get; set; } #endregion Data Properties #region Navigation Properties /// <summary>Gets or sets the TimeGroup. </summary> [ForeignKey("TimeGroupId")] [InverseProperty("TimeLimits")] public TimeGroup TimeGroup { get; set; } #endregion Navigation Properties } #endregion TimeLimit #region TimeGroup class // [DataContract(IsReference = true)] [Table("TimeGroup", Schema = "dbo")] public partial class TimeGroup { #region Data Properties [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } // [DataMember] [Column("Comment")] public string Comment { get; set; } #endregion Data Properties #region Navigation Properties // [DataMember] [InverseProperty("TimeGroup")] public ICollection<TimeLimit> TimeLimits { get; set; } #endregion Navigation Properties } #endregion TimeGroup #region Comment class // [DataContract(IsReference = true)] [Table("Comment", Schema = "dbo")] public partial class Comment { #region Data Properties [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("CreatedOn", Order = 1)] public System.DateTime CreatedOn { get; set; } [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("SeqNum", Order = 2)] public byte SeqNum { get; set; } // [DataMember] [Column("Comment1")] public string Comment1 { get; set; } #endregion Data Properties #region Navigation properties #endregion Navigation properties } #endregion Comment // #region Geospatial class // // [DataContract(IsReference = true)] // [Table("Geospatial", Schema = "dbo")] // public partial class Geospatial { // public Geospatial() { // this.Geometry1 = DbGeometry.FromText("POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))"); // this.Geography1 = DbGeography.FromText("MULTIPOINT(-122.360 47.656, -122.343 47.656)", 4326); // // this.Geometry1 = DbGeometry.FromText("GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10)"); // } // [Key] // // [DataMember] // [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // [Column("Id")] // public int Id { get; set; } // // [DataMember] // [Column("Geometry1")] // public DbGeometry Geometry1 { get; set; } // // [DataMember] // [Column("Geography1")] // public DbGeography Geography1 { get; set; } // } // #endregion Geospatial #region UnusualDate class // [DataContract(IsReference = true)] [Table("UnusualDate", Schema = "dbo")] public partial class UnusualDate { [Key] // [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } // [DataMember] [Column("CreationDate")] public System.DateTimeOffset CreationDate { get; set; } // [DataMember] [Column("ModificationDate")] public System.DateTime ModificationDate { get; set; } // [DataMember] [Column("CreationDate2")] public Nullable<System.DateTimeOffset> CreationDate2 { get; set; } // [DataMember] [Column("ModificationDate2")] public Nullable<System.DateTime> ModificationDate2 { get; set; } } #endregion UnusualDate }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; namespace System.Xml { internal class UTF16Decoder : System.Text.Decoder { private bool _bigEndian; private int _lastByte; private const int CharSize = 2; public UTF16Decoder(bool bigEndian) { _lastByte = -1; _bigEndian = bigEndian; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override int GetCharCount(byte[] bytes, int index, int count, bool flush) { int byteCount = count + ((_lastByte >= 0) ? 1 : 0); if (flush && (byteCount % CharSize != 0)) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, -1), (string)null); } return byteCount / CharSize; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); if (_lastByte >= 0) { if (byteCount == 0) { return charCount; } int nextByte = bytes[byteIndex++]; byteCount--; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); _lastByte = -1; } if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + --byteCount]; } // use the fast BlockCopy if possible if (_bigEndian == BitConverter.IsLittleEndian) { int byteEnd = byteIndex + byteCount; if (_bigEndian) { while (byteIndex < byteEnd) { int hi = bytes[byteIndex++]; int lo = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (byteIndex < byteEnd) { int lo = bytes[byteIndex++]; int hi = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount); } return charCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { charsUsed = 0; bytesUsed = 0; if (_lastByte >= 0) { if (byteCount == 0) { completed = true; return; } int nextByte = bytes[byteIndex++]; byteCount--; bytesUsed++; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); charCount--; charsUsed++; _lastByte = -1; } if (charCount * CharSize < byteCount) { byteCount = charCount * CharSize; completed = false; } else { completed = true; } if (_bigEndian == BitConverter.IsLittleEndian) { int i = byteIndex; int byteEnd = i + (byteCount & ~0x1); if (_bigEndian) { while (i < byteEnd) { int hi = bytes[i++]; int lo = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (i < byteEnd) { int lo = bytes[i++]; int hi = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1)); } charsUsed += byteCount / CharSize; bytesUsed += byteCount; if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + byteCount - 1]; } } } internal class SafeAsciiDecoder : Decoder { public SafeAsciiDecoder() { } public override int GetCharCount(byte[] bytes, int index, int count) { return count; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int i = byteIndex; int j = charIndex; while (i < byteIndex + byteCount) { chars[j++] = (char)bytes[i++]; } return byteCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (charCount < byteCount) { byteCount = charCount; completed = false; } else { completed = true; } int i = byteIndex; int j = charIndex; int byteEndIndex = byteIndex + byteCount; while (i < byteEndIndex) { chars[j++] = (char)bytes[i++]; } charsUsed = byteCount; bytesUsed = byteCount; } } internal class Ucs4Encoding : Encoding { internal Ucs4Decoder ucs4Decoder; public override string WebName { get { return this.EncodingName; } } public override Decoder GetDecoder() { return ucs4Decoder; } public override int GetByteCount(char[] chars, int index, int count) { return checked(count * 4); } public override int GetByteCount(char[] chars) { return chars.Length * 4; } public override byte[] GetBytes(string s) { return null; //ucs4Decoder.GetByteCount(chars, index, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return 0; } public override int GetMaxByteCount(int charCount) { return 0; } public override int GetCharCount(byte[] bytes, int index, int count) { return ucs4Decoder.GetCharCount(bytes, index, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return ucs4Decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public override int GetMaxCharCount(int byteCount) { return (byteCount + 3) / 4; } public override int CodePage { get { return 0; } } public override int GetCharCount(byte[] bytes) { return bytes.Length / 4; } public override Encoder GetEncoder() { return null; } internal static Encoding UCS4_Littleendian { get { return new Ucs4Encoding4321(); } } internal static Encoding UCS4_Bigendian { get { return new Ucs4Encoding1234(); } } internal static Encoding UCS4_2143 { get { return new Ucs4Encoding2143(); } } internal static Encoding UCS4_3412 { get { return new Ucs4Encoding3412(); } } } internal sealed class Ucs4Encoding1234 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0x00, 0x00, 0xfe, 0xff }; public Ucs4Encoding1234() { ucs4Decoder = new Ucs4Decoder1234(); } public override string EncodingName { get { return "ucs-4 (Bigendian)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xfe, 0xff }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding4321 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0xff, 0xfe, 0x00, 0x00 }; public Ucs4Encoding4321() { ucs4Decoder = new Ucs4Decoder4321(); } public override string EncodingName { get { return "ucs-4"; } } public override byte[] GetPreamble() { return new byte[4] { 0xff, 0xfe, 0x00, 0x00 }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding2143 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0x00, 0x00, 0xff, 0xfe }; public Ucs4Encoding2143() { ucs4Decoder = new Ucs4Decoder2143(); } public override string EncodingName { get { return "ucs-4 (order 2143)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xff, 0xfe }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding3412 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0xfe, 0xff, 0x00, 0x00 }; public Ucs4Encoding3412() { ucs4Decoder = new Ucs4Decoder3412(); } public override string EncodingName { get { return "ucs-4 (order 3412)"; } } public override byte[] GetPreamble() { return new byte[4] { 0xfe, 0xff, 0x00, 0x00 }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal abstract class Ucs4Decoder : Decoder { internal byte[] lastBytes = new byte[4]; internal int lastBytesCount = 0; public override int GetCharCount(byte[] bytes, int index, int count) { return (count + lastBytesCount) / 4; } internal abstract int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // finish a character from the bytes that were cached last time int i = lastBytesCount; if (lastBytesCount > 0) { // copy remaining bytes into the cache for (; lastBytesCount < 4 && byteCount > 0; lastBytesCount++) { lastBytes[lastBytesCount] = bytes[byteIndex]; byteIndex++; byteCount--; } // still not enough bytes -> return if (lastBytesCount < 4) { return 0; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); charIndex += i; lastBytesCount = 0; } else { i = 0; } // decode block of byte quadruplets i = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } return i; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { bytesUsed = 0; charsUsed = 0; // finish a character from the bytes that were cached last time int i = 0; int lbc = lastBytesCount; if (lbc > 0) { // copy remaining bytes into the cache for (; lbc < 4 && byteCount > 0; lbc++) { lastBytes[lbc] = bytes[byteIndex]; byteIndex++; byteCount--; bytesUsed++; } // still not enough bytes -> return if (lbc < 4) { lastBytesCount = lbc; completed = true; return; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); charIndex += i; charCount -= i; charsUsed = i; lastBytesCount = 0; // if that's all that was requested -> return if (charCount == 0) { completed = (byteCount == 0); return; } } else { i = 0; } // modify the byte count for GetFullChars depending on how many characters were requested if (charCount * 4 < byteCount) { byteCount = charCount * 4; completed = false; } else { completed = true; } bytesUsed += byteCount; // decode block of byte quadruplets charsUsed = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } } internal void Ucs4ToUTF16(uint code, char[] chars, int charIndex) { chars[charIndex] = (char)(XmlCharType.SurHighStart + (char)((code >> 16) - 1) + (char)((code >> 10) & 0x3F)); chars[charIndex + 1] = (char)(XmlCharType.SurLowStart + (char)(code & 0x3FF)); } } internal class Ucs4Decoder4321 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } }; internal class Ucs4Decoder1234 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder2143 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 1] << 24) | (bytes[i] << 16) | (bytes[i + 3] << 8) | bytes[i + 2]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder3412 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.PowerBIEmbedded { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// WorkspacesOperations operations. /// </summary> internal partial class WorkspacesOperations : IServiceOperations<PowerBIEmbeddedManagementClient>, IWorkspacesOperations { /// <summary> /// Initializes a new instance of the WorkspacesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal WorkspacesOperations(PowerBIEmbeddedManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the PowerBIEmbeddedManagementClient /// </summary> public PowerBIEmbeddedManagementClient Client { get; private set; } /// <summary> /// Retrieves all existing Power BI workspaces in the specified workspace /// collection. /// </summary> /// <param name='resourceGroupName'> /// Azure resource group /// </param> /// <param name='workspaceCollectionName'> /// Power BI Embedded Workspace Collection name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Workspace>>> ListWithHttpMessagesAsync(string resourceGroupName, string workspaceCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workspaceCollectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspaceCollectionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceCollectionName", workspaceCollectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBI/workspaceCollections/{workspaceCollectionName}/workspaces").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceCollectionName}", Uri.EscapeDataString(workspaceCollectionName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Workspace>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Workspace>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; [Flags] internal enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // // [FriendAccessAllowed] internal abstract class WinRTSynchronizationContextFactoryBase { public abstract SynchronizationContext Create(object coreDispatcher); } #endif //FEATURE_COMINTEROP public class SynchronizationContext { private SynchronizationContextProperties _props = SynchronizationContextProperties.None; public SynchronizationContext() { } // helper delegate to statically bind to Wait method private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); private static Type s_cachedPreparedType1; private static Type s_cachedPreparedType2; private static Type s_cachedPreparedType3; private static Type s_cachedPreparedType4; private static Type s_cachedPreparedType5; // protected so that only the derived sync context class can enable these flags [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and WinForms apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(s => s.d(s.state), (d, state), preferLocal: false); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } // Method called when the CLR does a wait operation [CLSCompliant(false)] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Method that can be called by Wait overrides [CLSCompliant(false)] protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles)); } return WaitHelperNative(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitHelperNative(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); public static void SetSynchronizationContext(SynchronizationContext syncContext) { Thread.CurrentThread.SynchronizationContext = syncContext; } public static SynchronizationContext Current { get { SynchronizationContext context = Thread.CurrentThread.SynchronizationContext; #if FEATURE_APPX if (context == null && AppDomain.IsAppXModel()) context = GetWinRTContext(); #endif return context; } } #if FEATURE_APPX private static SynchronizationContext GetWinRTContext() { Debug.Assert(Environment.IsWinRTSupported); Debug.Assert(AppDomain.IsAppXModel()); // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } private static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } } }
// 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.IO; using System.Linq; using System.Reflection; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase { private enum Operation { Add, Set, Remove, Last, } [Fact] public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new SortedDictionary<int, bool>(); var actual = ImmutableSortedDictionary<int, bool>.Empty; int seed = unchecked((int)DateTime.Now.Ticks); Debug.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int key; do { key = random.Next(); } while (expected.ContainsKey(key)); bool value = random.Next() % 2 == 0; Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value); expected.Add(key, value); actual = actual.Add(key, value); break; case Operation.Set: bool overwrite = expected.Count > 0 && random.Next() % 2 == 0; if (overwrite) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; } else { do { key = random.Next(); } while (expected.ContainsKey(key)); } value = random.Next() % 2 == 0; Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite); expected[key] = value; actual = actual.SetItem(key, value); break; case Operation.Remove: if (expected.Count > 0) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; Debug.WriteLine("Removing element \"{0}\" from the set.", key); Assert.True(expected.Remove(key)); actual = actual.Remove(key); } break; } Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList()); } } [Fact] public void AddExistingKeySameValueTest() { AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft"); AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void AddExistingKeyDifferentValueTest() { AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void ToUnorderedTest() { var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n)))); var unsortedMap = sortedMap.ToImmutableDictionary(); Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap); Assert.Equal(sortedMap.Count, unsortedMap.Count); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList()); } [Fact] public void SortChangeTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("Johnny")); Assert.False(map.ContainsKey("johnny")); var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, newMap.Count); Assert.True(newMap.ContainsKey("Johnny")); Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive } [Fact] public void InitialBulkAddUniqueTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("c", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(2, actual.Count); } [Fact] public void InitialBulkAddWithExactDuplicatesTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "b"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(1, actual.Count); } [Fact] public void ContainsValueTest() { this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper()); } [Fact] public void InitialBulkAddWithKeyCollisionTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); AssertExtensions.Throws<ArgumentException>(null, () => map.AddRange(uniqueEntries)); } [Fact] public void Create() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; var dictionary = ImmutableSortedDictionary.Create<string, string>(); Assert.Equal(0, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(pairs); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void ToImmutableSortedDictionary() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant()); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void WithComparers() { var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1"); Assert.Same(Comparer<string>.Default, map.KeyComparer); Assert.True(map.ContainsKey("a")); Assert.False(map.ContainsKey("A")); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); var cultureComparer = StringComparer.CurrentCulture; map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(cultureComparer, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersCollisions() { // First check where collisions have matching values. var map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "1"); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(1, map.Count); Assert.True(map.ContainsKey("a")); Assert.Equal("1", map["a"]); // Now check where collisions have conflicting values. map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3"); AssertExtensions.Throws<ArgumentException>(null, () => map.WithComparers(StringComparer.OrdinalIgnoreCase)); // Force all values to be considered equal. map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(EverythingEqual<string>.Default, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("b")); } [Fact] public void CollisionExceptionMessageContainsKey() { var map = ImmutableSortedDictionary.Create<string, string>() .Add("firstKey", "1").Add("secondKey", "2"); var exception = AssertExtensions.Throws<ArgumentException>(null, () => map.Add("firstKey", "3")); if (!PlatformDetection.IsNetNative) //.Net Native toolchain removes exception messages. { Assert.Contains("firstKey", exception.Message); } } [Fact] public void WithComparersEmptyCollection() { var map = ImmutableSortedDictionary.Create<string, string>(); Assert.Same(Comparer<string>.Default, map.KeyComparer); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } [Fact] public void Remove_KeyExists_RemovesKeyValuePair() { ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" } }.ToImmutableSortedDictionary(); Assert.Equal(0, dictionary.Remove(1).Count); } [Fact] public void Remove_FirstKey_RemovesKeyValuePair() { ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" }, { 2, "b" } }.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Remove(1).Count); } [Fact] public void Remove_SecondKey_RemovesKeyValuePair() { ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" }, { 2, "b" } }.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Remove(2).Count); } [Fact] public void Remove_KeyDoesntExist_DoesNothing() { ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" } }.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Remove(2).Count); Assert.Equal(1, dictionary.Remove(-1).Count); } [Fact] public void Remove_EmptyDictionary_DoesNothing() { ImmutableSortedDictionary<int, string> dictionary = ImmutableSortedDictionary<int, string>.Empty; Assert.Equal(0, dictionary.Remove(2).Count); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedDictionary.Create<string, int>()); ImmutableSortedDictionary<int, int> dict = ImmutableSortedDictionary.Create<int, int>().Add(1, 2).Add(2, 3).Add(3, 4); var info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict); object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedDictionary.Create<string, string>(), "_root"); DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); KeyValuePair<int, int>[] items = itemProperty.GetValue(info.Instance) as KeyValuePair<int, int>[]; Assert.Equal(dict, items); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedDictionary.Create<int, int>()); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance() { var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k); var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance_Empty() { var dictionary = ImmutableSortedDictionary<int, int>.Empty; var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText); } protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() { return ImmutableSortedDictionaryTest.Empty<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableSortedDictionary.Create<string, TValue>(comparer); } protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer; } internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root; } protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsValue(value)); Assert.True(map.Add(key, value).ContainsValue(value)); } private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } } }
#region UsingStatements using UnityEngine; using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// - Class for describing and drawing Bezier Curves /// - Efficiently handles approximate length calculation through 'dirty' system /// - Has static functions for getting points on curves constructed by Vector3 parameters (GetPoint, GetCubicPoint, GetQuadraticPoint, and GetLinearPoint) /// </summary> [ExecuteInEditMode] [Serializable] public class BezierCurve : MonoBehaviour { #region PublicVariables /// <summary> /// - the number of mid-points calculated for each pair of bezier points /// - used for drawing the curve in the editor /// - used for calculating the "length" variable /// </summary> public int resolution = 30; /// <summary> /// Gets or sets a value indicating whether this <see cref="BezierCurve"/> is dirty. /// </summary> /// <value> /// <c>true</c> if dirty; otherwise, <c>false</c>. /// </value> public bool dirty { get; private set; } /// <summary> /// - color this curve will be drawn with in the editor /// - set in the editor /// </summary> public Color drawColor = Color.white; #endregion #region PublicProperties /// <summary> /// - set in the editor /// - used to determine if the curve should be drawn as "closed" in the editor /// - used to determine if the curve's length should include the curve between the first and the last points in "points" array /// - setting this value will cause the curve to become dirty /// </summary> [SerializeField] private bool _close; public bool close { get { return _close; } set { if(_close == value) return; _close = value; dirty = true; } } /// <summary> /// - set internally /// - gets point corresponding to "index" in "points" array /// - does not allow direct set /// </summary> /// <param name='index'> /// - the index /// </param> public BezierPoint this[int index] { get { return points[index]; } } /// <summary> /// - number of points stored in 'points' variable /// - set internally /// - does not include "handles" /// </summary> /// <value> /// - The point count /// </value> public int pointCount { get { return points.Length; } } /// <summary> /// - The approximate length of the curve /// - recalculates if the curve is "dirty" /// </summary> private float _length; public float length { get { if(dirty) { _length = 0; for(int i = 0; i < points.Length - 1; i++){ _length += ApproximateLength(points[i], points[i + 1], resolution); } if(close) _length += ApproximateLength(points[points.Length - 1], points[0], resolution); dirty = false; } return _length; } } #endregion #region PrivateVariables /// <summary> /// - Array of point objects that make up this curve /// - Populated through editor /// </summary> [SerializeField] private BezierPoint[] points = new BezierPoint[0]; #endregion #region UnityFunctions void OnDrawGizmos () { Gizmos.color = drawColor; if(points.Length > 1){ for(int i = 0; i < points.Length - 1; i++){ DrawCurve(points[i], points[i+1], resolution); } if (close) DrawCurve(points[points.Length - 1], points[0], resolution); } } void Awake(){ dirty = true; } #endregion #region PublicFunctions /// <summary> /// - Adds the given point to the end of the curve ("points" array) /// </summary> /// <param name='point'> /// - The point to add. /// </param> public void AddPoint(BezierPoint point) { List<BezierPoint> tempArray = new List<BezierPoint>(points); tempArray.Add(point); points = tempArray.ToArray(); dirty = true; } /// <summary> /// - Adds a point at position /// </summary> /// <returns> /// - The point object /// </returns> /// <param name='position'> /// - Where to add the point /// </param> public BezierPoint AddPointAt(Vector3 position) { GameObject pointObject = new GameObject("Point "+pointCount); pointObject.transform.parent = transform; pointObject.transform.position = position; BezierPoint newPoint = pointObject.AddComponent<BezierPoint>(); newPoint.curve = this; return newPoint; } /// <summary> /// - Removes the given point from the curve ("points" array) /// </summary> /// <param name='point'> /// - The point to remove /// </param> public void RemovePoint(BezierPoint point) { List<BezierPoint> tempArray = new List<BezierPoint>(points); tempArray.Remove(point); points = tempArray.ToArray(); dirty = false; } /// <summary> /// - Gets a copy of the bezier point array used to define this curve /// </summary> /// <returns> /// - The cloned array of points /// </returns> public BezierPoint[] GetAnchorPoints() { return (BezierPoint[])points.Clone(); } /// <summary> /// - Gets the point at 't' percent along this curve /// </summary> /// <returns> /// - Returns the point at 't' percent /// </returns> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the curve (0 = 0%, 1 = 100%) /// </param> public Vector3 GetPointAt(float t) { if(t <= 0) return points[0].position; else if (t >= 1) return points[points.Length - 1].position; float totalPercent = 0; float curvePercent = 0; BezierPoint p1 = null; BezierPoint p2 = null; for(int i = 0; i < points.Length - 1; i++) { curvePercent = ApproximateLength(points[i], points[i + 1], 10) / length; if(totalPercent + curvePercent > t) { p1 = points[i]; p2 = points[i + 1]; break; } else totalPercent += curvePercent; } if(close && p1 == null) { p1 = points[points.Length - 1]; p2 = points[0]; } t -= totalPercent; return GetPoint(p1, p2, t / curvePercent); } /// <summary> /// - Get the index of the given point in this curve /// </summary> /// <returns> /// - The index, or -1 if the point is not found /// </returns> /// <param name='point'> /// - Point to search for /// </param> public int GetPointIndex(BezierPoint point) { int result = -1; for(int i = 0; i < points.Length; i++) { if(points[i] == point) { result = i; break; } } return result; } /// <summary> /// - Sets this curve to 'dirty' /// - Forces the curve to recalculate its length /// </summary> public void SetDirty() { dirty = true; } #endregion #region PublicStaticFunctions /// <summary> /// - Draws the curve in the Editor /// </summary> /// <param name='p1'> /// - The bezier point at the beginning of the curve /// </param> /// <param name='p2'> /// - The bezier point at the end of the curve /// </param> /// <param name='resolution'> /// - The number of segments along the curve to draw /// </param> public static void DrawCurve(BezierPoint p1, BezierPoint p2, int resolution) { int limit = resolution+1; float _res = resolution; Vector3 lastPoint = p1.position; Vector3 currentPoint = Vector3.zero; for(int i = 1; i < limit; i++){ currentPoint = GetPoint(p1, p2, i/_res); Gizmos.DrawLine(lastPoint, currentPoint); lastPoint = currentPoint; } } /// <summary> /// - Gets the point 't' percent along a curve /// - Automatically calculates for the number of relevant points /// </summary> /// <returns> /// - The point 't' percent along the curve /// </returns> /// <param name='p1'> /// - The bezier point at the beginning of the curve /// </param> /// <param name='p2'> /// - The bezier point at the end of the curve /// </param> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the curve (0 = 0%, 1 = 100%) /// </param> public static Vector3 GetPoint(BezierPoint p1, BezierPoint p2, float t) { if(p1.handle2 != Vector3.zero) { if(p2.handle1 != Vector3.zero) return GetCubicCurvePoint(p1.position, p1.globalHandle2, p2.globalHandle1, p2.position, t); else return GetQuadraticCurvePoint(p1.position, p1.globalHandle2, p2.position, t); } else { if(p2.handle1 != Vector3.zero) return GetQuadraticCurvePoint(p1.position, p2.globalHandle1, p2.position, t); else return GetLinearPoint(p1.position, p2.position, t); } } /// <summary> /// - Gets the point 't' percent along a third-order curve /// </summary> /// <returns> /// - The point 't' percent along the curve /// </returns> /// <param name='p1'> /// - The point at the beginning of the curve /// </param> /// <param name='p2'> /// - The second point along the curve /// </param> /// <param name='p3'> /// - The third point along the curve /// </param> /// <param name='p4'> /// - The point at the end of the curve /// </param> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the curve (0 = 0%, 1 = 100%) /// </param> public static Vector3 GetCubicCurvePoint(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, float t) { t = Mathf.Clamp01(t); Vector3 part1 = Mathf.Pow(1 - t, 3) * p1; Vector3 part2 = 3 * Mathf.Pow(1 - t, 2) * t * p2; Vector3 part3 = 3 * (1 - t) * Mathf.Pow(t, 2) * p3; Vector3 part4 = Mathf.Pow(t, 3) * p4; return part1 + part2 + part3 + part4; } /// <summary> /// - Gets the point 't' percent along a second-order curve /// </summary> /// <returns> /// - The point 't' percent along the curve /// </returns> /// <param name='p1'> /// - The point at the beginning of the curve /// </param> /// <param name='p2'> /// - The second point along the curve /// </param> /// <param name='p3'> /// - The point at the end of the curve /// </param> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the curve (0 = 0%, 1 = 100%) /// </param> public static Vector3 GetQuadraticCurvePoint(Vector3 p1, Vector3 p2, Vector3 p3, float t) { t = Mathf.Clamp01(t); Vector3 part1 = Mathf.Pow(1 - t, 2) * p1; Vector3 part2 = 2 * (1 - t) * t * p2; Vector3 part3 = Mathf.Pow(t, 2) * p3; return part1 + part2 + part3; } /// <summary> /// - Gets point 't' percent along a linear "curve" (line) /// - This is exactly equivalent to Vector3.Lerp /// </summary> /// <returns> /// - The point 't' percent along the curve /// </returns> /// <param name='p1'> /// - The point at the beginning of the line /// </param> /// <param name='p2'> /// - The point at the end of the line /// </param> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the line (0 = 0%, 1 = 100%) /// </param> public static Vector3 GetLinearPoint(Vector3 p1, Vector3 p2, float t) { return p1 + ((p2 - p1) * t); } /// <summary> /// - Gets point 't' percent along n-order curve /// </summary> /// <returns> /// - The point 't' percent along the curve /// </returns> /// <param name='t'> /// - Value between 0 and 1 representing the percent along the curve (0 = 0%, 1 = 100%) /// </param> /// <param name='points'> /// - The points used to define the curve /// </param> public static Vector3 GetPoint(float t, params Vector3[] points){ t = Mathf.Clamp01(t); int order = points.Length-1; Vector3 point = Vector3.zero; Vector3 vectorToAdd; for(int i = 0; i < points.Length; i++){ vectorToAdd = points[points.Length-i-1] * (BinomialCoefficient(i, order) * Mathf.Pow(t, order-i) * Mathf.Pow((1-t), i)); point += vectorToAdd; } return point; } /// <summary> /// - Approximates the length /// </summary> /// <returns> /// - The approximate length /// </returns> /// <param name='p1'> /// - The bezier point at the start of the curve /// </param> /// <param name='p2'> /// - The bezier point at the end of the curve /// </param> /// <param name='resolution'> /// - The number of points along the curve used to create measurable segments /// </param> public static float ApproximateLength(BezierPoint p1, BezierPoint p2, int resolution = 10) { float _res = resolution; float total = 0; Vector3 lastPosition = p1.position; Vector3 currentPosition; for(int i = 0; i < resolution + 1; i++) { currentPosition = GetPoint(p1, p2, i / _res); total += (currentPosition - lastPosition).magnitude; lastPosition = currentPosition; } return total; } #endregion #region UtilityFunctions private static int BinomialCoefficient(int i, int n){ return Factoral(n)/(Factoral(i)*Factoral(n-i)); } private static int Factoral(int i){ if(i == 0) return 1; int total = 1; while(i-1 >= 0){ total *= i; i--; } return total; } #endregion /* needs testing public Vector3 GetPointAtDistance(float distance) { if(close) { if(distance < 0) while(distance < 0) { distance += length; } else if(distance > length) while(distance > length) { distance -= length; } } else { if(distance <= 0) return points[0].position; else if(distance >= length) return points[points.Length - 1].position; } float totalLength = 0; float curveLength = 0; BezierPoint firstPoint = null; BezierPoint secondPoint = null; for(int i = 0; i < points.Length - 1; i++) { curveLength = ApproximateLength(points[i], points[i + 1], resolution); if(totalLength + curveLength >= distance) { firstPoint = points[i]; secondPoint = points[i+1]; break; } else totalLength += curveLength; } if(firstPoint == null) { firstPoint = points[points.Length - 1]; secondPoint = points[0]; curveLength = ApproximateLength(firstPoint, secondPoint, resolution); } distance -= totalLength; return GetPoint(distance / curveLength, firstPoint, secondPoint); } */ }
using System; using System.Collections; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Concurrency; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Collections.Specialized; using System.Linq; using System.Reactive.Subjects; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Threading; using System.Reactive.Disposables; using System.Globalization; using System.Diagnostics; namespace ReactiveUIMicro { public class ReactiveCollection<T> : IList<T>, IList, INotifyPropertyChanging, INotifyPropertyChanged, INotifyCollectionChanged, IEnableLogger { public event NotifyCollectionChangedEventHandler CollectionChanging; public event NotifyCollectionChangedEventHandler CollectionChanged; public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; [field: IgnoreDataMember] bool rxObjectsSetup = false; [IgnoreDataMember] Subject<NotifyCollectionChangedEventArgs> _changing; [IgnoreDataMember] Subject<NotifyCollectionChangedEventArgs> _changed; [DataMember] List<T> _inner; [IgnoreDataMember] int _suppressionRefCount = 0; [IgnoreDataMember] Lazy<Subject<T>> _beforeItemsAdded; [IgnoreDataMember] Lazy<Subject<T>> _itemsAdded; [IgnoreDataMember] Lazy<Subject<T>> _beforeItemsRemoved; [IgnoreDataMember] Lazy<Subject<T>> _itemsRemoved; [IgnoreDataMember] Lazy<Subject<IObservedChange<T, object>>> _itemChanging; [IgnoreDataMember] Lazy<Subject<IObservedChange<T, object>>> _itemChanged; [IgnoreDataMember] Lazy<Subject<IMoveInfo<T>>> _beforeItemsMoved; [IgnoreDataMember] Lazy<Subject<IMoveInfo<T>>> _itemsMoved; [IgnoreDataMember] Dictionary<object, RefcountDisposeWrapper> _propertyChangeWatchers = null; [IgnoreDataMember] int _resetSubCount = 0; static bool _hasWhinedAboutNoResetSub = false; // NB: This exists so the serializer doesn't whine // // 2nd NB: VB.NET doesn't deal well with default parameters, create // some overloads so people can continue to make bad life choices instead // of using C# public ReactiveCollection() { setupRx(); } public ReactiveCollection(IEnumerable<T> initialContents) { setupRx(initialContents); } public ReactiveCollection(IEnumerable<T> initialContents = null, IScheduler scheduler = null, double resetChangeThreshold = 0.3) { setupRx(initialContents, scheduler, resetChangeThreshold); } [OnDeserialized] #if WP7 public #endif void setupRx(StreamingContext _) { setupRx(); } void setupRx(IEnumerable<T> initialContents = null, IScheduler scheduler = null, double resetChangeThreshold = 0.3) { if (rxObjectsSetup) return; scheduler = scheduler ?? RxApp.DeferredScheduler; _inner = _inner ?? new List<T>(); _changing = new Subject<NotifyCollectionChangedEventArgs>(); _changing.Subscribe(raiseCollectionChanging); _changed = new Subject<NotifyCollectionChangedEventArgs>(); _changed.Subscribe(raiseCollectionChanged); ResetChangeThreshold = resetChangeThreshold; _beforeItemsAdded = new Lazy<Subject<T>>(() => new Subject<T>()); _itemsAdded = new Lazy<Subject<T>>(() => new Subject<T>()); _beforeItemsRemoved = new Lazy<Subject<T>>(() => new Subject<T>()); _itemsRemoved = new Lazy<Subject<T>>(() => new Subject<T>()); _itemChanging = new Lazy<Subject<IObservedChange<T, object>>>(() => new Subject<IObservedChange<T, object>>()); _itemChanged = new Lazy<Subject<IObservedChange<T, object>>>(() => new Subject<IObservedChange<T, object>>()); _beforeItemsMoved = new Lazy<Subject<IMoveInfo<T>>>(() => new Subject<IMoveInfo<T>>()); _itemsMoved = new Lazy<Subject<IMoveInfo<T>>>(() => new Subject<IMoveInfo<T>>()); // NB: We have to do this instead of initializing _inner so that // Collection<T>'s accounting is correct foreach (var item in initialContents ?? Enumerable.Empty<T>()) { Add(item); } // NB: ObservableCollection has a Secret Handshake with WPF where // they fire an INPC notification with the token "Item[]". Emulate // it here CollectionCountChanging.Select(x => new PropertyChangingEventArgs("Count")).Subscribe(this.raisePropertyChanging); CollectionCountChanged.Select(x => new PropertyChangedEventArgs("Count")).Subscribe(this.raisePropertyChanged); Changing.Select(x => new PropertyChangingEventArgs("Item[]")).Subscribe(this.raisePropertyChanging); Changed.Select(x => new PropertyChangedEventArgs("Item[]")).Subscribe(this.raisePropertyChanged); rxObjectsSetup = true; } /* * Collection<T> core methods */ protected void InsertItem(int index, T item) { if (_suppressionRefCount > 0) { _inner.Insert(index, item); if (ChangeTrackingEnabled) addItemToPropertyTracking(item); return; } var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index); _changing.OnNext(ea); if (_beforeItemsAdded.IsValueCreated) _beforeItemsAdded.Value.OnNext(item); _inner.Insert(index, item); _changed.OnNext(ea); if (_itemsAdded.IsValueCreated) _itemsAdded.Value.OnNext(item); if (ChangeTrackingEnabled) addItemToPropertyTracking(item); } protected void RemoveItem(int index) { var item = _inner[index]; if (_suppressionRefCount > 0) { _inner.RemoveAt(index); if (ChangeTrackingEnabled) removeItemFromPropertyTracking(item); return; } var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index); _changing.OnNext(ea); if (_beforeItemsRemoved.IsValueCreated) _beforeItemsRemoved.Value.OnNext(item); _inner.RemoveAt(index); _changed.OnNext(ea); if (_itemsRemoved.IsValueCreated) _itemsRemoved.Value.OnNext(item); if (ChangeTrackingEnabled) removeItemFromPropertyTracking(item); } #if !SILVERLIGHT protected void MoveItem(int oldIndex, int newIndex) { var item = _inner[oldIndex]; if (_suppressionRefCount > 0) { _inner.RemoveAt(oldIndex); _inner.Insert(newIndex, item); return; } var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex); var mi = new MoveInfo<T>(new[] { item }, oldIndex, newIndex); _changing.OnNext(ea); if (_beforeItemsMoved.IsValueCreated) _beforeItemsMoved.Value.OnNext(mi); _inner.RemoveAt(oldIndex); _inner.Insert(newIndex, item); _changed.OnNext(ea); if (_itemsMoved.IsValueCreated) _itemsMoved.Value.OnNext(mi); } #endif protected void SetItem(int index, T item) { if (_suppressionRefCount > 0) { _inner[index] = item; if (ChangeTrackingEnabled) { removeItemFromPropertyTracking(_inner[index]); addItemToPropertyTracking(item); } return; } var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, _inner[index], index); _changing.OnNext(ea); if (ChangeTrackingEnabled) { removeItemFromPropertyTracking(_inner[index]); addItemToPropertyTracking(item); } _inner[index] = item; _changed.OnNext(ea); } protected void ClearItems() { if (_suppressionRefCount > 0) { _inner.Clear(); if (ChangeTrackingEnabled) clearAllPropertyChangeWatchers(); return; } var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); _changing.OnNext(ea); _inner.Clear(); _changed.OnNext(ea); if (ChangeTrackingEnabled) clearAllPropertyChangeWatchers(); } /* * List<T> methods we can make faster by possibly sending ShouldReset * notifications instead of thrashing the UI by readding items * one at a time */ public double ResetChangeThreshold { get; set; } public virtual void AddRange(IEnumerable<T> collection) { InsertRange(_inner.Count, collection); } public virtual void InsertRange(int index, IEnumerable<T> collection) { var arr = collection.ToArray(); var disp = isLengthAboveResetThreshold(arr.Length) ? SuppressChangeNotifications() : Disposable.Empty; using (disp) { // NB: If we don't do this, we'll break Collection<T>'s // accounting of the length for (int i = arr.Length - 1; i >= 0; i--) { InsertItem(index, arr[i]); } } } public virtual void RemoveRange(int index, int count) { var disp = isLengthAboveResetThreshold(count) ? SuppressChangeNotifications() : Disposable.Empty; using (disp) { // NB: If we don't do this, we'll break Collection<T>'s // accounting of the length for (int i = count; i > 0; i--) { RemoveItem(index); } } } public virtual void RemoveAll(IEnumerable<T> items) { Contract.Requires(items != null); var disp = isLengthAboveResetThreshold(items.Count()) ? SuppressChangeNotifications() : Disposable.Empty; using (disp) { // NB: If we don't do this, we'll break Collection<T>'s // accounting of the length foreach (var v in items) { Remove(v); } } } public virtual void Sort(int index, int count, IComparer<T> comparer) { _inner.Sort(index, count, comparer); Reset(); } public virtual void Sort(Comparison<T> comparison) { _inner.Sort(comparison); Reset(); } public virtual void Sort(IComparer<T> comparer = null) { _inner.Sort(comparer ?? Comparer<T>.Default); Reset(); } public virtual void Reset() { publishResetNotification(); } protected virtual void publishResetNotification() { var ea = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); _changing.OnNext(ea); _changed.OnNext(ea); } bool isLengthAboveResetThreshold(int toChangeLength) { return (double) toChangeLength/_inner.Count > ResetChangeThreshold && toChangeLength > 10; } /* * IReactiveCollection<T> */ public bool ChangeTrackingEnabled { get { return _propertyChangeWatchers != null; } set { if (_propertyChangeWatchers != null && value) return; if (_propertyChangeWatchers == null && !value) return; if (value) { _propertyChangeWatchers = new Dictionary<object, RefcountDisposeWrapper>(); foreach (var item in _inner) { addItemToPropertyTracking(item); } } else { clearAllPropertyChangeWatchers(); _propertyChangeWatchers = null; } } } public IDisposable SuppressChangeNotifications() { Interlocked.Increment(ref _suppressionRefCount); if (!_hasWhinedAboutNoResetSub && _resetSubCount == 0 && CollectionChanged == null) { LogHost.Default.Warn("SuppressChangeNotifications was called (perhaps via AddRange), yet you do not"); LogHost.Default.Warn("have a subscription to ShouldReset. This probably isn't what you want, as ItemsAdded"); LogHost.Default.Warn("and friends will appear to 'miss' items"); _hasWhinedAboutNoResetSub = true; } return Disposable.Create(() => { if (Interlocked.Decrement(ref _suppressionRefCount) == 0) { publishResetNotification(); } }); } public IObservable<T> BeforeItemsAdded { get { return _beforeItemsAdded.Value; } } public IObservable<T> ItemsAdded { get { return _itemsAdded.Value; } } public IObservable<T> BeforeItemsRemoved { get { return _beforeItemsRemoved.Value; } } public IObservable<T> ItemsRemoved { get { return _itemsRemoved.Value; } } public IObservable<IMoveInfo<T>> BeforeItemsMoved { get { return _beforeItemsMoved.Value; } } public IObservable<IMoveInfo<T>> ItemsMoved { get { return _itemsMoved.Value; } } public IObservable<IObservedChange<T, object>> ItemChanging { get { return _itemChanging.Value; } } public IObservable<IObservedChange<T, object>> ItemChanged { get { return _itemChanged.Value; } } public IObservable<int> CollectionCountChanging { get { return _changing.Select(_ => _inner.Count).DistinctUntilChanged(); } } public IObservable<int> CollectionCountChanged { get { return _changed.Select(_ => _inner.Count).DistinctUntilChanged(); } } public IObservable<bool> IsEmpty { get { return _changed.Select(_ => _inner.Count == 0).DistinctUntilChanged(); } } public IObservable<NotifyCollectionChangedEventArgs> Changing { get { return _changing; } } public IObservable<NotifyCollectionChangedEventArgs> Changed { get { return _changed; } } public IObservable<Unit> ShouldReset { get { return refcountSubscribers(_changed.SelectMany(x => x.Action != NotifyCollectionChangedAction.Reset ? Observable.Empty<Unit>() : Observable.Return(Unit.Default)), x => _resetSubCount += x); } } /* * Property Change Tracking */ void addItemToPropertyTracking(T toTrack) { if (_propertyChangeWatchers.ContainsKey(toTrack)) { _propertyChangeWatchers[toTrack].AddRef(); return; } var changing = Observable.Never<IObservedChange<object, object>>(); var changed = Observable.Never<IObservedChange<object, object>>(); var irnpc = toTrack as IReactiveNotifyPropertyChanged; if (irnpc != null) { changing = irnpc.Changing; changed = irnpc.Changed; goto isSetup; } var inpc = toTrack as INotifyPropertyChanged; if (inpc != null) { changed = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(x => inpc.PropertyChanged += x, x => inpc.PropertyChanged -= x) .Select(x => (IObservedChange<object, object>) new ObservedChange<object, object>() { PropertyName = x.EventArgs.PropertyName, Sender = inpc }); goto isSetup; } this.Log().Warn("Property change notifications are enabled and type {0} isn't INotifyPropertyChanged or ReactiveObject", typeof(T)); isSetup: var toDispose = new[] { changing.Where(_ => _suppressionRefCount == 0).Subscribe(beforeChange => _itemChanging.Value.OnNext(new ObservedChange<T, object>() { Sender = toTrack, PropertyName = beforeChange.PropertyName })), changed.Where(_ => _suppressionRefCount == 0).Subscribe(change => _itemChanged.Value.OnNext(new ObservedChange<T,object>() { Sender = toTrack, PropertyName = change.PropertyName })), }; _propertyChangeWatchers.Add(toTrack, new RefcountDisposeWrapper(Disposable.Create(() => { toDispose[0].Dispose(); toDispose[1].Dispose(); _propertyChangeWatchers.Remove(toTrack); }))); } void removeItemFromPropertyTracking(T toUntrack) { _propertyChangeWatchers[toUntrack].Release(); } void clearAllPropertyChangeWatchers() { while (_propertyChangeWatchers.Count > 0) _propertyChangeWatchers.Values.First().Release(); } static IObservable<TObs> refcountSubscribers<TObs>(IObservable<TObs> input, Action<int> block) { return Observable.Create<TObs>(subj => { block(1); return new CompositeDisposable( input.Subscribe(subj), Disposable.Create(() => block(-1))); }); } protected virtual void raiseCollectionChanging(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = this.CollectionChanging; if (handler != null && _suppressionRefCount == 0) { handler(this, e); } } protected virtual void raiseCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = this.CollectionChanged; if (handler != null && _suppressionRefCount == 0) { handler(this, e); } } protected virtual void raisePropertyChanging(PropertyChangingEventArgs e) { PropertyChangingEventHandler handler = this.PropertyChanging; if (handler != null && _suppressionRefCount == 0) { handler(this, e); } } protected virtual void raisePropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null && _suppressionRefCount == 0) { handler(this, e); } } #region Super Boring IList crap public IEnumerator<T> GetEnumerator() { return _inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public virtual void Add(T item) { InsertItem(_inner.Count, item); } public virtual void Clear() { ClearItems(); } public bool Contains(T item) { return _inner.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _inner.CopyTo(array, arrayIndex); } public virtual bool Remove(T item) { int index = _inner.IndexOf(item); if (index < 0) return false; RemoveItem(index); return true; } public int Count { get { return _inner.Count; } } public virtual bool IsReadOnly { get { return false; } } public int IndexOf(T item) { return _inner.IndexOf(item); } public virtual void Insert(int index, T item) { InsertItem(index, item); } public virtual void RemoveAt(int index) { RemoveItem(index); } #if !SILVERLIGHT public virtual void Move(int oldIndex, int newIndex) { MoveItem(oldIndex, newIndex); } #endif public virtual T this[int index] { get { return _inner[index]; } set { SetItem(index, value); } } public int Add(object value) { Add((T)value); return Count - 1; } public bool Contains(object value) { return IsCompatibleObject(value) && Contains((T)value); } public int IndexOf(object value) { return IsCompatibleObject(value) ? IndexOf((T)value) : -1; } public void Insert(int index, object value) { Insert(index, (T)value); } public bool IsFixedSize { get { return false; } } public void Remove(object value) { if (IsCompatibleObject(value)) Remove((T)value); } object IList.this[int index] { get { return this[index]; } set { this[index] = (T)value; } } public void CopyTo(Array array, int index) { ((IList)_inner).CopyTo(array, index); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } private static bool IsCompatibleObject(object value) { return ((value is T) || ((value == null) && (default(T) == null))); } #endregion } #if WP7 public interface IMoveInfo<T> #else public interface IMoveInfo<out T> #endif { IEnumerable<T> MovedItems { get; } int From { get; } int To { get; } } public class MoveInfo<T> : IMoveInfo<T> { public IEnumerable<T> MovedItems { get; protected set; } public int From { get; protected set; } public int To { get; protected set; } public MoveInfo(IEnumerable<T> movedItems, int from, int to) { MovedItems = movedItems; From = from; To = to; } } } // vim: tw=120 ts=4 sw=4 et :
// 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.Text.RegularExpressions; using System.Globalization; using Xunit; public class RegexLangElementsCoverageTests { // This class mainly exists to hit language elements that were missed in other test cases. [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void RegexLangElementsCoverage() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; int iCountErrors = 0; int iCountTestcases = 0; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// //AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoadEventHandler; for (int i = 0; i < s_regexTests.Length; i++) { try { iCountTestcases++; if (!s_regexTests[i].Run()) { Console.WriteLine("Err_79872asnko! Test {0} FAILED Pattern={1}, Input={2}\n", i, s_regexTests[i].Pattern, s_regexTests[i].Input); iCountErrors++; } } catch (Exception e) { Console.WriteLine("Err_79872asnko! Test {0} FAILED Pattern={1}, Input={2} threw the following exception:", i, s_regexTests[i].Pattern, s_regexTests[i].Input); Console.WriteLine(e); iCountErrors++; } } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } //private const int GERMAN_PHONEBOOK = 0x10407; //private const int ENGLISH_US = 0x0409; //private const int INVARIANT = 0x007F; //private const int CZECH = 0x0405; //private const int DANISH = 0x0406; //private const int TURKISH = 0x041F; //private const int LATIN_AZERI = 0x042C; private static CultureInfo _GERMAN_PHONEBOOK = new CultureInfo("de-DE"); private static CultureInfo _ENGLISH_US = new CultureInfo("en-US"); private static CultureInfo _INVARIANT = new CultureInfo(""); private static CultureInfo _CZECH = new CultureInfo("cs-CZ"); private static CultureInfo _DANISH = new CultureInfo("da-DK"); private static CultureInfo _TURKISH = new CultureInfo("tr-TR"); private static CultureInfo _LATIN_AZERI = new CultureInfo("az-Latn-AZ"); private static RegexTestCase[] s_regexTests = new RegexTestCase[] { /********************************************************* Unicode Char Classes *********************************************************/ new RegexTestCase(@"(\p{Lu}\w*)\s(\p{Lu}\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\p{Lu}\p{Ll}*)\s(\p{Lu}\p{Ll}*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\P{Ll}\p{Ll}*)\s(\P{Ll}\p{Ll}*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\P{Lu}+\p{Lu})\s(\P{Lu}+\p{Lu})", "hellO worlD", new string[] {"hellO worlD", "hellO", "worlD"}), new RegexTestCase(@"(\p{Lt}\w*)\s(\p{Lt}*\w*)", "\u01C5ello \u01C5orld", new string[] {"\u01C5ello \u01C5orld", "\u01C5ello", "\u01C5orld"}), new RegexTestCase(@"(\P{Lt}\w*)\s(\P{Lt}*\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), /********************************************************* Character ranges IgnoreCase *********************************************************/ new RegexTestCase(@"[@-D]+", RegexOptions.IgnoreCase, "eE?@ABCDabcdeE", new string[] {"@ABCDabcd"}), new RegexTestCase(@"[>-D]+", RegexOptions.IgnoreCase, "eE=>?@ABCDabcdeE", new string[] {">?@ABCDabcd"}), new RegexTestCase(@"[\u0554-\u0557]+", RegexOptions.IgnoreCase, "\u0583\u0553\u0554\u0555\u0556\u0584\u0585\u0586\u0557\u0558", new string[] {"\u0554\u0555\u0556\u0584\u0585\u0586\u0557"}), new RegexTestCase(@"[X-\]]+", RegexOptions.IgnoreCase, "wWXYZxyz[\\]^", new string[] {"XYZxyz[\\]"}), new RegexTestCase(@"[X-\u0533]+", RegexOptions.IgnoreCase, "\u0551\u0554\u0560AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563\u0564", new string[] {"AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563"}), new RegexTestCase(@"[X-a]+", RegexOptions.IgnoreCase, "wWAXYZaxyz", new string[] {"AXYZaxyz"}), new RegexTestCase(@"[X-c]+", RegexOptions.IgnoreCase, "wWABCXYZabcxyz", new string[] {"ABCXYZabcxyz"}), new RegexTestCase(@"[X-\u00C0]+", RegexOptions.IgnoreCase, "\u00C1\u00E1\u00C0\u00E0wWABCXYZabcxyz", new string[] {"\u00C0\u00E0wWABCXYZabcxyz"}), new RegexTestCase(@"[\u0100\u0102\u0104]+", RegexOptions.IgnoreCase, "\u00FF \u0100\u0102\u0104\u0101\u0103\u0105\u0106", new string[] {"\u0100\u0102\u0104\u0101\u0103\u0105"}), new RegexTestCase(@"[B-D\u0130]+", RegexOptions.IgnoreCase, "aAeE\u0129\u0131\u0068 BCDbcD\u0130\u0069\u0070", new string[] {"BCDbcD\u0130\u0069"}), new RegexTestCase(@"[\u013B\u013D\u013F]+", RegexOptions.IgnoreCase, "\u013A\u013B\u013D\u013F\u013C\u013E\u0140\u0141", new string[] {"\u013B\u013D\u013F\u013C\u013E\u0140"}), new RegexTestCase(@"[\uFFFD-\uFFFF]+", RegexOptions.IgnoreCase, "\uFFFC\uFFFD\uFFFE\uFFFF", new string[] {"\uFFFD\uFFFE\uFFFF"}), new RegexTestCase(@"[\uFFFC-\uFFFE]+", RegexOptions.IgnoreCase, "\uFFFB\uFFFC\uFFFD\uFFFE\uFFFF", new string[] {"\uFFFC\uFFFD\uFFFE"}), /********************************************************* Escape Chars *********************************************************/ new RegexTestCase("(Cat)\r(Dog)", "Cat\rDog", new string[] {"Cat\rDog", "Cat", "Dog"}), new RegexTestCase("(Cat)\t(Dog)", "Cat\tDog", new string[] {"Cat\tDog", "Cat", "Dog"}), new RegexTestCase("(Cat)\f(Dog)", "Cat\fDog", new string[] {"Cat\fDog", "Cat", "Dog"}), /********************************************************* Miscellaneous { witout matching } *********************************************************/ new RegexTestCase(@"\p{klsak", typeof(ArgumentException)), new RegexTestCase(@"{5", "hello {5 world", new string[] {"{5"}), new RegexTestCase(@"{5,", "hello {5, world", new string[] {"{5,"}), new RegexTestCase(@"{5,6", "hello {5,6 world", new string[] {"{5,6"}), /********************************************************* Miscellaneous inline options *********************************************************/ new RegexTestCase(@"(?r:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?c:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?n:(?<cat>cat)(\s+)(?<dog>dog))", "cat dog", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(?n:(cat)(\s+)(dog))", "cat dog", new string[] {"cat dog"}), new RegexTestCase(@"(?n:(cat)(?<SpaceChars>\s+)(dog))", "cat dog", new string[] {"cat dog", " "}), new RegexTestCase(@"(?x: (?<cat>cat) # Cat statement (\s+) # Whitespace chars (?<dog>dog # Dog statement ))", "cat dog", new string[] {"cat dog", " ", "cat", "dog"}), new RegexTestCase(@"(?e:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?+i:cat)", "CAT", new string[] {"CAT"}), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p inside character range *********************************************************/ new RegexTestCase(@"cat([\d]*)dog", "hello123cat230927dog1412d", new string[] {"cat230927dog", "230927"}), new RegexTestCase(@"([\D]*)dog", "65498catdog58719", new string[] {"catdog", "cat"}), new RegexTestCase(@"cat([\s]*)dog", "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"cat([\S]*)", "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\w]*)", "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\W]*)dog", "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"cat([a-\d]*)dog", typeof(ArgumentException)), new RegexTestCase(@"([5-\D]*)dog", typeof(ArgumentException)), new RegexTestCase(@"cat([6-\s]*)dog", typeof(ArgumentException)), new RegexTestCase(@"cat([c-\S]*)", typeof(ArgumentException)), new RegexTestCase(@"cat([7-\w]*)", typeof(ArgumentException)), new RegexTestCase(@"cat([a-\W]*)dog", typeof(ArgumentException)), new RegexTestCase(@"([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)", typeof(ArgumentException)), new RegexTestCase(@"([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", typeof(ArgumentException)), new RegexTestCase(@"[\p]", typeof(ArgumentException)), new RegexTestCase(@"[\P]", typeof(ArgumentException)), new RegexTestCase(@"([\pcat])", typeof(ArgumentException)), new RegexTestCase(@"([\Pcat])", typeof(ArgumentException)), new RegexTestCase(@"(\p{", typeof(ArgumentException)), new RegexTestCase(@"(\p{Ll", typeof(ArgumentException)), /********************************************************* \x, \u, \a, \b, \e, \f, \n, \r, \t, \v, \c, inside character range *********************************************************/ new RegexTestCase(@"(cat)([\x41]*)(dog)", "catAAAdog", new String[] {"catAAAdog", "cat", "AAA", "dog"}), new RegexTestCase(@"(cat)([\u0041]*)(dog)", "catAAAdog", new String[] {"catAAAdog", "cat", "AAA", "dog"}), new RegexTestCase(@"(cat)([\a]*)(dog)", "cat\a\a\adog", new String[] {"cat\a\a\adog", "cat", "\a\a\a", "dog"}), new RegexTestCase(@"(cat)([\b]*)(dog)", "cat\b\b\bdog", new String[] {"cat\b\b\bdog", "cat", "\b\b\b", "dog"}), new RegexTestCase(@"(cat)([\e]*)(dog)", "cat\u001B\u001B\u001Bdog", new String[] {"cat\u001B\u001B\u001Bdog", "cat", "\u001B\u001B\u001B", "dog"}), new RegexTestCase(@"(cat)([\f]*)(dog)", "cat\f\f\fdog", new String[] {"cat\f\f\fdog", "cat", "\f\f\f", "dog"}), new RegexTestCase(@"(cat)([\r]*)(dog)", "cat\r\r\rdog", new String[] {"cat\r\r\rdog", "cat", "\r\r\r", "dog"}), new RegexTestCase(@"(cat)([\v]*)(dog)", "cat\v\v\vdog", new String[] {"cat\v\v\vdog", "cat", "\v\v\v", "dog"}), new RegexTestCase(@"(cat)([\o]*)(dog)", typeof(ArgumentException)), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p inside character range ([0-5]) with ECMA Option *********************************************************/ new RegexTestCase(@"cat([\d]*)dog", RegexOptions.ECMAScript, "hello123cat230927dog1412d", new string[] {"cat230927dog", "230927"}), new RegexTestCase(@"([\D]*)dog", RegexOptions.ECMAScript, "65498catdog58719", new string[] {"catdog", "cat"}), new RegexTestCase(@"cat([\s]*)dog", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"cat([\S]*)", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\w]*)", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\W]*)dog", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "Hello", "World"}), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p outside character range ([0-5]) with ECMA Option *********************************************************/ new RegexTestCase(@"(cat)\d*dog", RegexOptions.ECMAScript, "hello123cat230927dog1412d", new string[] {"cat230927dog", "cat"}), new RegexTestCase(@"\D*(dog)", RegexOptions.ECMAScript, "65498catdog58719", new string[] {"catdog", "dog"}), new RegexTestCase(@"(cat)\s*(dog)", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\S*", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "cat"}), new RegexTestCase(@"(cat)\w*", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "cat"}), new RegexTestCase(@"(cat)\W*(dog)", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"\p{Lu}(\w*)\s\p{Lu}(\w*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "ello", "orld"}), new RegexTestCase(@"\P{Ll}\p{Ll}*\s\P{Ll}\p{Ll}*", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World"}), /********************************************************* Use < in a group *********************************************************/ new RegexTestCase(@"cat(?<0>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<1dog>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog!>)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog >)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog<>)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<->dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog121>dog)", "catcatdogdogcat", new string[] {"catdog", "dog"}), new RegexTestCase(@"(?<cat>cat)\s*(?<cat>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<1>cat)\s*(?<1>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<2048>cat)\s*(?<2048>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", ""}), new RegexTestCase(@"(?<cat>cat)\w+(?<cat-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "_Hello_World_"}), new RegexTestCase(@"(?<1>cat)\w+(?<dog-1>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<2-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<1>cat)\w+(?<2-1>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-16>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-1uosn>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-catdog>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-()*!@>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", null), /********************************************************* Quantifiers *********************************************************/ new RegexTestCase(@"(?<cat>cat){", "STARTcat{", new string[] {"cat{", "cat"}), new RegexTestCase(@"(?<cat>cat){fdsa", "STARTcat{fdsa", new string[] {"cat{fdsa", "cat"}), new RegexTestCase(@"(?<cat>cat){1", "STARTcat{1", new string[] {"cat{1", "cat"}), new RegexTestCase(@"(?<cat>cat){1END", "STARTcat{1END", new string[] {"cat{1END", "cat"}), new RegexTestCase(@"(?<cat>cat){1,", "STARTcat{1,", new string[] {"cat{1,", "cat"}), new RegexTestCase(@"(?<cat>cat){1,END", "STARTcat{1,END", new string[] {"cat{1,END", "cat"}), new RegexTestCase(@"(?<cat>cat){1,2", "STARTcat{1,2", new string[] {"cat{1,2", "cat"}), new RegexTestCase(@"(?<cat>cat){1,2END", "STARTcat{1,2END", new string[] {"cat{1,2END", "cat"}), /********************************************************* Use (? in a group *********************************************************/ new RegexTestCase(@"cat(?(?#COMMENT)cat)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?'cat'cat)dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?<cat>cat)dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?afdcat)dog)", typeof(ArgumentException)), /********************************************************* Use IgnorePatternWhitespace *********************************************************/ new RegexTestCase(@"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog ", RegexOptions.IgnorePatternWhitespace, "cat dog", new String[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog", RegexOptions.IgnorePatternWhitespace, "cat dog", new String[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace) (dog) (?#followed by dog)", RegexOptions.IgnorePatternWhitespace, "cat dog", new String[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.IgnorePatternWhitespace, typeof(ArgumentException)), /********************************************************* Without IgnorePatternWhitespace *********************************************************/ new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", typeof(ArgumentException)), /********************************************************* Back Reference *********************************************************/ new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<cat>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k'cat'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\<cat>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\'cat'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<1>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k'1'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\<1>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\'1'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\1", RegexOptions.ECMAScript, "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<dog>", "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\2", RegexOptions.ECMAScript, "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\kcat", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<cat2>", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.ECMAScript, typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k8", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.ECMAScript, typeof(ArgumentException)), /********************************************************* Octal *********************************************************/ new RegexTestCase(@"(cat)(\077)", "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\77)", "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\176)", "hellocat~dogworld", new string[] {"cat~", "cat", "~"}), new RegexTestCase(@"(cat)(\400)", "hellocat\0dogworld", new string[] {"cat\0", "cat", "\0"}), new RegexTestCase(@"(cat)(\300)", "hellocat\u00C0dogworld", new string[] {"cat\u00C0", "cat", "\u00C0"}), new RegexTestCase(@"(cat)(\300)", "hellocat\u00C0dogworld", new string[] {"cat\u00C0", "cat", "\u00C0"}), new RegexTestCase(@"(cat)(\477)", "hellocat\u003Fdogworld", new string[] {"cat\u003F", "cat", "\u003F"}), new RegexTestCase(@"(cat)(\777)", "hellocat\u00FFdogworld", new string[] {"cat\u00FF", "cat", "\u00FF"}), new RegexTestCase(@"(cat)(\7770)", "hellocat\u00FF0dogworld", new string[] {"cat\u00FF0", "cat", "\u00FF0"}), new RegexTestCase(@"(cat)(\7)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\077)", RegexOptions.ECMAScript, "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\77)", RegexOptions.ECMAScript, "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\7)", RegexOptions.ECMAScript, "hellocat\adogworld", new string[] {"cat\a", "cat", "\a"}), new RegexTestCase(@"(cat)(\40)", RegexOptions.ECMAScript, "hellocat dogworld", new string[] {"cat ", "cat", " "}), new RegexTestCase(@"(cat)(\040)", RegexOptions.ECMAScript, "hellocat dogworld", new string[] {"cat ", "cat", " "}), new RegexTestCase(@"(cat)(\176)", RegexOptions.ECMAScript, "hellocatcat76dogworld", new string[] {"catcat76", "cat", "cat76"}), new RegexTestCase(@"(cat)(\377)", RegexOptions.ECMAScript, "hellocat\u00FFdogworld", new string[] {"cat\u00FF", "cat", "\u00FF"}), new RegexTestCase(@"(cat)(\400)", RegexOptions.ECMAScript, "hellocat 0Fdogworld", new string[] {"cat 0", "cat", " 0"}), /********************************************************* Decimal *********************************************************/ new RegexTestCase(@"(cat)\s+(?<2147483646>dog)", "asdlkcat dogiwod", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(?<2147483647>dog)", "asdlkcat dogiwod", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(?<2147483648>dog)", typeof(System.ArgumentException)), new RegexTestCase(@"(cat)\s+(?<21474836481097>dog)", typeof(System.ArgumentException)), /********************************************************* Hex *********************************************************/ new RegexTestCase(@"(cat)(\x2a*)(dog)", "asdlkcat***dogiwod", new string[] {"cat***dog", "cat", "***", "dog"}), new RegexTestCase(@"(cat)(\x2b*)(dog)", "asdlkcat+++dogiwod", new string[] {"cat+++dog", "cat", "+++", "dog"}), new RegexTestCase(@"(cat)(\x2c*)(dog)", "asdlkcat,,,dogiwod", new string[] {"cat,,,dog", "cat", ",,,", "dog"}), new RegexTestCase(@"(cat)(\x2d*)(dog)", "asdlkcat---dogiwod", new string[] {"cat---dog", "cat", "---", "dog"}), new RegexTestCase(@"(cat)(\x2e*)(dog)", "asdlkcat...dogiwod", new string[] {"cat...dog", "cat", "...", "dog"}), new RegexTestCase(@"(cat)(\x2f*)(dog)", "asdlkcat///dogiwod", new string[] {"cat///dog", "cat", "///", "dog"}), new RegexTestCase(@"(cat)(\x2A*)(dog)", "asdlkcat***dogiwod", new string[] {"cat***dog", "cat", "***", "dog"}), new RegexTestCase(@"(cat)(\x2B*)(dog)", "asdlkcat+++dogiwod", new string[] {"cat+++dog", "cat", "+++", "dog"}), new RegexTestCase(@"(cat)(\x2C*)(dog)", "asdlkcat,,,dogiwod", new string[] {"cat,,,dog", "cat", ",,,", "dog"}), new RegexTestCase(@"(cat)(\x2D*)(dog)", "asdlkcat---dogiwod", new string[] {"cat---dog", "cat", "---", "dog"}), new RegexTestCase(@"(cat)(\x2E*)(dog)", "asdlkcat...dogiwod", new string[] {"cat...dog", "cat", "...", "dog"}), new RegexTestCase(@"(cat)(\x2F*)(dog)", "asdlkcat///dogiwod", new string[] {"cat///dog", "cat", "///", "dog"}), /********************************************************* ScanControl *********************************************************/ new RegexTestCase(@"(cat)(\c*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)\c", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c *)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c?*)(dog)", typeof(ArgumentException)), new RegexTestCase("(cat)(\\c\0*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c`*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c\|*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c\[*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c@*)(dog)", "asdlkcat\0\0dogiwod", new string[] {"cat\0\0dog", "cat", "\0\0", "dog"}), new RegexTestCase(@"(cat)(\cA*)(dog)", "asdlkcat\u0001dogiwod", new string[] {"cat\u0001dog", "cat", "\u0001", "dog"}), new RegexTestCase(@"(cat)(\ca*)(dog)", "asdlkcat\u0001dogiwod", new string[] {"cat\u0001dog", "cat", "\u0001", "dog"}), new RegexTestCase(@"(cat)(\cC*)(dog)", "asdlkcat\u0003dogiwod", new string[] {"cat\u0003dog", "cat", "\u0003", "dog"}), new RegexTestCase(@"(cat)(\cc*)(dog)", "asdlkcat\u0003dogiwod", new string[] {"cat\u0003dog", "cat", "\u0003", "dog"}), new RegexTestCase(@"(cat)(\cD*)(dog)", "asdlkcat\u0004dogiwod", new string[] {"cat\u0004dog", "cat", "\u0004", "dog"}), new RegexTestCase(@"(cat)(\cd*)(dog)", "asdlkcat\u0004dogiwod", new string[] {"cat\u0004dog", "cat", "\u0004", "dog"}), new RegexTestCase(@"(cat)(\cX*)(dog)", "asdlkcat\u0018dogiwod", new string[] {"cat\u0018dog", "cat", "\u0018", "dog"}), new RegexTestCase(@"(cat)(\cx*)(dog)", "asdlkcat\u0018dogiwod", new string[] {"cat\u0018dog", "cat", "\u0018", "dog"}), new RegexTestCase(@"(cat)(\cZ*)(dog)", "asdlkcat\u001adogiwod", new string[] {"cat\u001adog", "cat", "\u001a", "dog"}), new RegexTestCase(@"(cat)(\cz*)(dog)", "asdlkcat\u001adogiwod", new string[] {"cat\u001adog", "cat", "\u001a", "dog"}), /********************************************************* Atomic Zero-Width Assertions \A \Z \z \G \b \B *********************************************************/ //\A new RegexTestCase(@"\A(cat)\s+(dog)", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", null), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.Multiline, "cat \n\n\ncat dog", null), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.ECMAScript, "cat \n\n\ncat dog", null), //\Z new RegexTestCase(@"(cat)\s+(dog)\Z", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", null), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat dog\n\n\ncat ", null), //\z new RegexTestCase(@"(cat)\s+(dog)\z", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", "cat dog\n\n\ncat", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat \n\n\n dog\n", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat \n\n\n dog\n", null), //\b new RegexTestCase(@"\b@cat", "123START123@catEND", new string[] {"@cat"}), new RegexTestCase(@"\b\<cat", "123START123<catEND", new string[] {"<cat"}), new RegexTestCase(@"\b,cat", "satwe,,,START,catEND", new string[] {",cat"}), new RegexTestCase(@"\b\[cat", "`12START123[catEND", new string[] {"[cat"}), new RegexTestCase(@"\b@cat", "123START123;@catEND", null), new RegexTestCase(@"\b\<cat", "123START123'<catEND", null), new RegexTestCase(@"\b,cat", "satwe,,,START',catEND", null), new RegexTestCase(@"\b\[cat", "`12START123'[catEND", null), //\B new RegexTestCase(@"\B@cat", "123START123;@catEND", new string[] {"@cat"}), new RegexTestCase(@"\B\<cat", "123START123'<catEND", new string[] {"<cat"}), new RegexTestCase(@"\B,cat", "satwe,,,START',catEND", new string[] {",cat"}), new RegexTestCase(@"\B\[cat", "`12START123'[catEND", new string[] {"[cat"}), new RegexTestCase(@"\B@cat", "123START123@catEND", null), new RegexTestCase(@"\B\<cat", "123START123<catEND", null), new RegexTestCase(@"\B,cat", "satwe,,,START,catEND", null), new RegexTestCase(@"\B\[cat", "`12START123[catEND", null), /********************************************************* \w matching \p{Lm} (Letter, Modifier) *********************************************************/ new RegexTestCase(@"(\w+)\s+(\w+)", "cat\u02b0 dog\u02b1", new string[] {"cat\u02b0 dog\u02b1", "cat\u02b0", "dog\u02b1"}), new RegexTestCase(@"(cat\w+)\s+(dog\w+)", "STARTcat\u30FC dog\u3005END", new string[] {"cat\u30FC dog\u3005END", "cat\u30FC", "dog\u3005END"}), new RegexTestCase(@"(cat\w+)\s+(dog\w+)", "STARTcat\uff9e dog\uff9fEND", new string[] {"cat\uff9e dog\uff9fEND", "cat\uff9e", "dog\uff9fEND"}), /********************************************************* positive and negative character classes [a-c]|[^b-c] *********************************************************/ new RegexTestCase(@"[^a]|d", "d", new string[] {"d"}), new RegexTestCase(@"([^a]|[d])*", "Hello Worlddf", new string[] {"Hello Worlddf", "f"}), new RegexTestCase(@"([^{}]|\n)+", "{{{{Hello\n World \n}END", new string[] {"Hello\n World \n", "\n"}), new RegexTestCase(@"([a-d]|[^abcd])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), new RegexTestCase(@"([^a]|[a])*", "once upon a time", new string[] {"once upon a time", "e"}), new RegexTestCase(@"([a-d]|[^abcd]|[x-z]|^wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), new RegexTestCase(@"([a-d]|[e-i]|[^e]|wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), /********************************************************* canonical and noncanonical char class, where one group is in it's simplest form [a-e] and another is more complex . *********************************************************/ new RegexTestCase(@"^(([^b]+ )|(.* ))$", "aaa ", new string[] {"aaa ", "aaa ", "aaa ", ""}), new RegexTestCase(@"^(([^b]+ )|(.*))$", "aaa", new string[] {"aaa", "aaa", "", "aaa"}), new RegexTestCase(@"^(([^b]+ )|(.* ))$", "bbb ", new string[] {"bbb ", "bbb ", "", "bbb "}), new RegexTestCase(@"^(([^b]+ )|(.*))$", "bbb", new string[] {"bbb", "bbb", "", "bbb"}), new RegexTestCase(@"^((a*)|(.*))$", "aaa", new string[] {"aaa", "aaa", "aaa", ""}), new RegexTestCase(@"^((a*)|(.*))$", "aaabbb", new string[] {"aaabbb", "aaabbb", "", "aaabbb"}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{hello 1234567890 world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{hello 1234567890 world}", new string[] {"hello", "o", "", "o", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{HELLO 1234567890 world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{HELLO 1234567890 world}", new string[] {"HELLO", "O", "", "", "O"}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{1234567890 hello world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{1234567890 hello world}", new string[] {"1234567890", "0", "0", "", ""}), new RegexTestCase(@"^(([a-d]*)|([a-z]*))$", "aaabbbcccdddeeefff", new string[] {"aaabbbcccdddeeefff", "aaabbbcccdddeeefff", "", "aaabbbcccdddeeefff"}), new RegexTestCase(@"^(([d-f]*)|([c-e]*))$", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "", "dddeeeccceee"}), new RegexTestCase(@"^(([c-e]*)|([d-f]*))$", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), new RegexTestCase(@"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", new string[] {"aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", ""}), new RegexTestCase(@"(([d-f]*)|([c-e]*))", "dddeeeccceee", new string[] {"dddeee", "dddeee", "dddeee", ""}), new RegexTestCase(@"(([c-e]*)|([d-f]*))", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), new RegexTestCase(@"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", new string[] {"aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", ""}), new RegexTestCase(@"(([d-f]*)|(.*))", "dddeeeccceee", new string[] {"dddeee", "dddeee", "dddeee", ""}), new RegexTestCase(@"(([c-e]*)|(.*))", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), /********************************************************* \p{Pi} (Punctuation Initial quote) \p{Pf} (Punctuation Final quote) *********************************************************/ new RegexTestCase(@"\p{Pi}(\w*)\p{Pf}", "\u00ABCat\u00BB \u00BBDog\u00AB'", new string[] {"\u00ABCat\u00BB", "Cat"}), new RegexTestCase(@"\p{Pi}(\w*)\p{Pf}", "\u2018Cat\u2019 \u2019Dog\u2018'", new string[] {"\u2018Cat\u2019", "Cat"}), /********************************************************* Use special unicode characters *********************************************************/ /* new RegexTest(@"AE", "\u00C4", new string[] {"Hello World", "Hello", "World"}, GERMAN_PHONEBOOK), new RegexTest(@"oe", "\u00F6", new string[] {"Hello World", "Hello", "World"}, GERMAN_PHONEBOOK), new RegexTest("\u00D1", "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00D1", "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00D1", RegexOptions.IgnoreCase, "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00D1", RegexOptions.IgnoreCase, "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00F1", RegexOptions.IgnoreCase, "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00F1", RegexOptions.IgnoreCase, "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00F1", "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00F1", "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), */ new RegexTestCase("CH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _ENGLISH_US), new RegexTestCase("CH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _CZECH), new RegexTestCase("cH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _ENGLISH_US), new RegexTestCase("cH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _CZECH), new RegexTestCase("AA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _ENGLISH_US), new RegexTestCase("AA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _DANISH), new RegexTestCase("aA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _ENGLISH_US), new RegexTestCase("aA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _DANISH), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _TURKISH), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _TURKISH), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _LATIN_AZERI), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _LATIN_AZERI), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", null, _ENGLISH_US), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0069", null, _ENGLISH_US), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _ENGLISH_US), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _ENGLISH_US), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", null, _INVARIANT), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0069", null, _INVARIANT), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0049", null, _INVARIANT), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", null, _INVARIANT), /********************************************************* ECMAScript *********************************************************/ new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\s+\123\s+\234", RegexOptions.ECMAScript, "asdfcat dog cat23 dog34eia", new string[] {"cat dog cat23 dog34", "cat", "dog"}), /********************************************************* Balanced Matching *********************************************************/ new RegexTestCase(@"<div> (?> <div>(?<DEPTH>) | </div> (?<-DEPTH>) | .? )*? (?(DEPTH)(?!)) </div>", RegexOptions.IgnorePatternWhitespace, "<div>this is some <div>red</div> text</div></div></div>", new string[] {"<div>this is some <div>red</div> text</div>", ""}), new RegexTestCase(@"( ((?'open'<+)[^<>]*)+ ((?'close-open'>+)[^<>]*)+ )+", RegexOptions.IgnorePatternWhitespace, "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", new string[] {"<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", "<02deep_03<03deep_03>>>", "<03deep_03", ">>>", "<", "03deep_03"}), new RegexTestCase(@"( (?<start><)? [^<>]? (?<end-start>>)? )*", RegexOptions.IgnorePatternWhitespace, "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", new string[] {"<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", "", "", "01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>"}), new RegexTestCase(@"( (?<start><[^/<>]*>)? [^<>]? (?<end-start></[^/<>]*>)? )*", RegexOptions.IgnorePatternWhitespace, "<b><a>Cat</a></b>", new string[] {"<b><a>Cat</a></b>", "", "", "<a>Cat</a>"}), new RegexTestCase(@"( (?<start><(?<TagName>[^/<>]*)>)? [^<>]? (?<end-start></\k<TagName>>)? )*", RegexOptions.IgnorePatternWhitespace, "<b>cat</b><a>dog</a>", new string[] {"<b>cat</b><a>dog</a>", "", "", "a", "dog"}), /********************************************************* Balanced Matching With Backtracking *********************************************************/ new RegexTestCase(@"( (?<start><[^/<>]*>)? .? (?<end-start></[^/<>]*>)? )* (?(start)(?!)) ", RegexOptions.IgnorePatternWhitespace, "<b><a>Cat</a></b><<<<c>>>><<d><e<f>><g><<<>>>>", new string[] {"<b><a>Cat</a></b><<<<c>>>><<d><e<f>><g><<<>>>>", "", "", "<a>Cat"}), /********************************************************* Character Classes and Lazy quantifier *********************************************************/ new RegexTestCase(@"([0-9]+?)([\w]+?)", RegexOptions.ECMAScript, "55488aheiaheiad", new string[] {"55", "5", "5"}), new RegexTestCase(@"([0-9]+?)([a-z]+?)", RegexOptions.ECMAScript, "55488aheiaheiad", new string[] {"55488a", "55488", "a"}), /********************************************************* Miscellaneous/Regression scenarios *********************************************************/ new RegexTestCase(@"(?<openingtag>1)(?<content>.*?)(?=2)", RegexOptions.Singleline | RegexOptions.ExplicitCapture, "1" + Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>" + Environment.NewLine + "2", new string[] {"1" + Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>" + Environment.NewLine, "1", Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>"+ Environment.NewLine }), new RegexTestCase(@"\G<%#(?<code>.*?)?%>", RegexOptions.Singleline, @"<%# DataBinder.Eval(this, ""MyNumber"") %>", new string[] {@"<%# DataBinder.Eval(this, ""MyNumber"") %>", @" DataBinder.Eval(this, ""MyNumber"") "}), /********************************************************* Nested Quantifiers *********************************************************/ new RegexTestCase(@"^[abcd]{0,0x10}*$", "a{0,0x10}}}", new string[] {"a{0,0x10}}}"}), new RegexTestCase(@"^[abcd]{0,16}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1,}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{0,16}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1,}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*+$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*?+$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]??*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*{0,5}$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+{0,5}$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]?{0,5}$", typeof(ArgumentException)), /********************************************************* Lazy operator Backtracking *********************************************************/ new RegexTestCase(@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", RegexOptions.IgnoreCase, "http://www.msn.com", null), new RegexTestCase(@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", RegexOptions.IgnoreCase, "http://www.msn.com/", new string[] {"http://www.msn.com/", "com", String.Empty}), new RegexTestCase(@"http://([a-zA-Z0-9\-]*\.?)*?/", RegexOptions.IgnoreCase, @"http://www.google.com/", new string[] {"http://www.google.com/", "com"}), new RegexTestCase(@"([a-z]*?)([\w])", RegexOptions.IgnoreCase, "cat", new string[] {"c", String.Empty, "c"}), new RegexTestCase(@"^([a-z]*?)([\w])$", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), // TODO: Come up with more scenarios here /********************************************************* Backtracking *********************************************************/ new RegexTestCase(@"([a-z]*)([\w])", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), new RegexTestCase(@"^([a-z]*)([\w])$", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), // TODO: Come up with more scenarios here /********************************************************* Character Escapes Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"\u", typeof(ArgumentException)), new RegexTestCase(@"\ua", typeof(ArgumentException)), new RegexTestCase(@"\u0", typeof(ArgumentException)), new RegexTestCase(@"\x", typeof(ArgumentException)), new RegexTestCase(@"\x2", typeof(ArgumentException)), /********************************************************* Character class Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"[", typeof(ArgumentException)), new RegexTestCase(@"[]", typeof(ArgumentException)), new RegexTestCase(@"[a", typeof(ArgumentException)), new RegexTestCase(@"[^", typeof(ArgumentException)), new RegexTestCase(@"[cat", typeof(ArgumentException)), new RegexTestCase(@"[^cat", typeof(ArgumentException)), new RegexTestCase(@"[a-", typeof(ArgumentException)), new RegexTestCase(@"[a-]+", "ba-b", new string[] {"a-"}), new RegexTestCase(@"\p{", typeof(ArgumentException)), new RegexTestCase(@"\p{cat", typeof(ArgumentException)), new RegexTestCase(@"\p{cat}", typeof(ArgumentException)), new RegexTestCase(@"\P{", typeof(ArgumentException)), new RegexTestCase(@"\P{cat", typeof(ArgumentException)), new RegexTestCase(@"\P{cat}", typeof(ArgumentException)), /********************************************************* Quantifiers *********************************************************/ new RegexTestCase(@"(cat){", "cat{", new string[] {"cat{", "cat"}), new RegexTestCase(@"(cat){}", "cat{}", new string[] {"cat{}", "cat"}), new RegexTestCase(@"(cat){,", "cat{,", new string[] {"cat{,", "cat"}), new RegexTestCase(@"(cat){,}", "cat{,}", new string[] {"cat{,}", "cat"}), new RegexTestCase(@"(cat){cat}", "cat{cat}", new string[] {"cat{cat}", "cat"}), new RegexTestCase(@"(cat){cat,5}", "cat{cat,5}", new string[] {"cat{cat,5}", "cat"}), new RegexTestCase(@"(cat){5,dog}", "cat{5,dog}", new string[] {"cat{5,dog}", "cat"}), new RegexTestCase(@"(cat){cat,dog}", "cat{cat,dog}", new string[] {"cat{cat,dog}", "cat"}), new RegexTestCase(@"(cat){,}?", "cat{,}?", new string[] {"cat{,}", "cat"}), new RegexTestCase(@"(cat){cat}?", "cat{cat}?", new string[] {"cat{cat}", "cat"}), new RegexTestCase(@"(cat){cat,5}?", "cat{cat,5}?", new string[] {"cat{cat,5}", "cat"}), new RegexTestCase(@"(cat){5,dog}?", "cat{5,dog}?", new string[] {"cat{5,dog}", "cat"}), new RegexTestCase(@"(cat){cat,dog}?", "cat{cat,dog}?", new string[] {"cat{cat,dog}", "cat"}), /********************************************************* Grouping Constructs Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"(", typeof(ArgumentException)), new RegexTestCase(@"(?", typeof(ArgumentException)), new RegexTestCase(@"(?<", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>", typeof(ArgumentException)), new RegexTestCase(@"(?'", typeof(ArgumentException)), new RegexTestCase(@"(?'cat'", typeof(ArgumentException)), new RegexTestCase(@"(?:", typeof(ArgumentException)), new RegexTestCase(@"(?imn", typeof(ArgumentException)), new RegexTestCase(@"(?imn )", typeof(ArgumentException)), new RegexTestCase(@"(?=", typeof(ArgumentException)), new RegexTestCase(@"(?!", typeof(ArgumentException)), new RegexTestCase(@"(?<=", typeof(ArgumentException)), new RegexTestCase(@"(?<!", typeof(ArgumentException)), new RegexTestCase(@"(?>", typeof(ArgumentException)), new RegexTestCase(@"()", "cat", new string[] {String.Empty, String.Empty}), new RegexTestCase(@"(?)", typeof(ArgumentException)), new RegexTestCase(@"(?<)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>)", "cat", new string[] {String.Empty, String.Empty}), new RegexTestCase(@"(?')", typeof(ArgumentException)), new RegexTestCase(@"(?'cat')", "cat", new string[] {String.Empty, String.Empty}), new RegexTestCase(@"(?:)", "cat", new string[] {String.Empty}), new RegexTestCase(@"(?imn)", "cat", new string[] {String.Empty}), new RegexTestCase(@"(?imn)cat", "(?imn)cat", new string[] {"cat"}), new RegexTestCase(@"(?=)", "cat", new string[] {String.Empty}), new RegexTestCase(@"(?!)", "(?!)cat"), new RegexTestCase(@"(?<=)", "cat", new string[] {String.Empty}), new RegexTestCase(@"(?<!)", "(?<!)cat"), new RegexTestCase(@"(?>)", "cat", new string[] {String.Empty}), /********************************************************* Grouping Constructs Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"\1", typeof(ArgumentException)), new RegexTestCase(@"\1", typeof(ArgumentException)), new RegexTestCase(@"\k", typeof(ArgumentException)), new RegexTestCase(@"\k<", typeof(ArgumentException)), new RegexTestCase(@"\k<1", typeof(ArgumentException)), new RegexTestCase(@"\k<cat", typeof(ArgumentException)), new RegexTestCase(@"\k<>", typeof(ArgumentException)), /********************************************************* Alternation construct Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"(?(", typeof(ArgumentException)), new RegexTestCase(@"(?()|", typeof(ArgumentException)), new RegexTestCase(@"(?()|)", "(?()|)", new string[] {""}), new RegexTestCase(@"(?(cat", typeof(ArgumentException)), new RegexTestCase(@"(?(cat)|", typeof(ArgumentException)), new RegexTestCase(@"(?(cat)|)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)catdog|)", "catdog", new string[] {"catdog"}), new RegexTestCase(@"(?(cat)catdog|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)dog|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)dog|)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|catdog)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|catdog)", "catdog", new string[] {""}), new RegexTestCase(@"(?(cat)|dog)", "dog", new string[] {"dog"}), new RegexTestCase(@"(?(cat)|dog)", "oof"), /********************************************************* Empty Match *********************************************************/ new RegexTestCase(@"([a*]*)+?$", "ab", new string[] {"", ""}), new RegexTestCase(@"(a*)+?$", "b", new string[] {"", ""}), }; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using MyGeneration.Forms; using Scintilla; using Scintilla.Configuration.Legacy; using Scintilla.Forms; using WeifenLuo.WinFormsUI.Docking; using Zeus; namespace MyGeneration { public partial class MyGenerationMDI : Form, IMyGenerationMDI { private const string DOCK_CONFIG_FILE = @"\settings\dock.config"; private const string SCINTILLA_CONFIG_FILE = @"\settings\scintillanet.xml"; private const string REPLACEMENT_SUFFIX = "$REPLACEMENT$.dll"; private static ConfigFile _configFile; private ScintillaConfigureDelegate _scintillaConfigureDelegate; private readonly Dictionary<string, IMyGenContent> _dynamicContentWindows = new Dictionary<string, IMyGenContent>(); private LanguageMappings _languageMappings; private DbTargetMappings _dbTargetMappings; private MetaDataBrowser _metaDataBrowser; private UserMetaData _userMetaData; private GlobalUserMetaData _globalUserMetaData; private MetaProperties _metaProperties; private DefaultSettingsDialog _defaultSettingsDialog; private TemplateBrowser _templateBrowser; private ConsoleForm _consoleForm; private ErrorsForm _errorsForm; private ErrorDetail _errorDetail; private GeneratedFilesForm _generatedFilesForm; private readonly string _startupPath; private readonly string[] _startupFiles; public MyGenerationMDI(string startupPath, params string[] args) { _startupPath = startupPath; // if the command line arguments contain a new location for the config file, set it. var argsList = new List<string>(); string lastArg = null; foreach (string arg in args) { if (lastArg == "-configfile") { string file = Zeus.FileTools.MakeAbsolute(arg, FileTools.AssemblyPath); if (File.Exists(file)) { DefaultSettings.SettingsFileName = file; } } else { argsList.Add(arg); } lastArg = arg; } // Any files that were locked when the TemplateLibrary downloaded // and tried to replace them will be replaced now. ProcessReplacementFiles(); InitializeComponent(); _startupFiles = argsList.ToArray(); EditorManager.AddNewDocumentMenuItems(newFileDynamicToolStripMenuItem_Click, newToolStripMenuItem.DropDownItems, toolStripDropDownButtonNew.DropDownItems); ContentManager.AddNewContentMenuItems(openContentDynamicToolStripMenuItem_Click, pluginsToolStripMenuItem, toolStrip1); PluginManager.AddHelpMenuItems(HelpMenuItem_OnClicked, helpToolStripMenuItem, 2); RefreshRecentFiles(); } #region Loading private void MyGenerationMDI_OnLoad(object sender, EventArgs e) { RestoreWindowState(); LoadScintillaConfiguration(); LoadDockContentConfiguration(); if (_startupFiles != null) { OpenDocuments(_startupFiles); } } private void LoadDockContentConfiguration() { var deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString); var dockConfigFileName = _startupPath + DOCK_CONFIG_FILE; if (!File.Exists(dockConfigFileName)) return; try { MainDockPanel.LoadFromXml(dockConfigFileName, deserializeDockContent); } catch (Exception) { try { File.Delete(dockConfigFileName); } catch { } } } private void LoadScintillaConfiguration() { var scintillaConfigFile = new FileInfo(_startupPath + SCINTILLA_CONFIG_FILE); if (scintillaConfigFile.Exists) { var maxTries = 3; while (maxTries > 0) { try { _configFile = new ConfigurationUtility().LoadConfiguration(scintillaConfigFile.FullName) as ConfigFile; break; } catch { if (--maxTries == 1) { File.Copy(scintillaConfigFile.FullName, scintillaConfigFile.FullName + ".tmp", true); scintillaConfigFile = new FileInfo(scintillaConfigFile.FullName + ".tmp"); } else { Thread.Sleep(10); } } } } if (_configFile == null) return; _scintillaConfigureDelegate = _configFile.MasterScintilla.Configure; ZeusScintillaControl.StaticConfigure = _scintillaConfigureDelegate; } private void RestoreWindowState() { switch (DefaultSettings.Instance.WindowState) { case "Maximized": WindowState = FormWindowState.Maximized; break; case "Minimized": WindowState = FormWindowState.Minimized; break; case "Normal": var x = Convert.ToInt32(DefaultSettings.Instance.WindowPosLeft); var y = Convert.ToInt32(DefaultSettings.Instance.WindowPosTop); var w = Convert.ToInt32(DefaultSettings.Instance.WindowPosWidth); var h = Convert.ToInt32(DefaultSettings.Instance.WindowPosHeight); Location = new Point(x, y); Size = new Size(w, h); break; } } #endregion #region Closing private void MyGenerationMDI_FormClosing(object sender, FormClosingEventArgs e) { var allowPrevent = true; var allowSave = true; if (e.CloseReason == CloseReason.TaskManagerClosing) { allowSave = false; } else if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.ApplicationExitCall) { allowPrevent = false; } if (!ZeusProcessManager.IsDormant) { var dialogResult = MessageBox.Show(this, "There are templates currently being executed. Would you like to kill them?", "Warning", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { ZeusProcessManager.KillAll(); } else { e.Cancel = true; return; } } if (allowSave && !Shutdown(allowPrevent)) { e.Cancel = true; } else { SaveWindowState(); } } private void SaveWindowState() { try { switch (WindowState) { case FormWindowState.Maximized: DefaultSettings.Instance.WindowState = "Maximized"; break; case FormWindowState.Minimized: DefaultSettings.Instance.WindowState = "Minimized"; break; case FormWindowState.Normal: DefaultSettings.Instance.WindowState = "Normal"; DefaultSettings.Instance.WindowPosLeft = Location.X.ToString(); DefaultSettings.Instance.WindowPosTop = Location.Y.ToString(); DefaultSettings.Instance.WindowPosWidth = Size.Width.ToString(); DefaultSettings.Instance.WindowPosHeight = Size.Height.ToString(); break; } DefaultSettings.Instance.Save(); } catch { } } #endregion private void PickFiles() { var openFileDialog = new OpenFileDialog { InitialDirectory = Directory.GetCurrentDirectory(), Filter = EditorManager.OpenFileDialogString, RestoreDirectory = true, Multiselect = true }; if (openFileDialog.ShowDialog() == DialogResult.OK) { OpenDocuments(openFileDialog.FileNames); } } private void OpenContent(params string[] keys) { foreach (var key in keys) { if (_dynamicContentWindows.ContainsKey(key)) { IMyGenContent mygenContent = _dynamicContentWindows[key]; if (mygenContent.DockContent.Visible) { mygenContent.DockContent.Hide(); } else { mygenContent.DockContent.Show(MainDockPanel); } } else { IMyGenContent mygenContent = ContentManager.CreateContent(this, key); if (mygenContent != null) { _dynamicContentWindows[key] = mygenContent; mygenContent.DockContent.Show(MainDockPanel); } } } } private void ExecuteSimplePlugin(params string[] keys) { try { foreach (string key in keys) { if (PluginManager.SimplePluginManagers.ContainsKey(key)) { PluginManager.SimplePluginManagers[key].Execute(this); } } } catch (Exception ex) { ErrorsOccurred(ex); } } public void CreateDocument(params string[] fileTypes) { foreach (var fileType in fileTypes) { IMyGenDocument mygenDoc = EditorManager.CreateDocument(this, fileType); if (mygenDoc != null) mygenDoc.DockContent.Show(MainDockPanel); } } public void OpenDocuments(params string[] filenames) { foreach (var file in filenames) { var info = new FileInfo(file); if (!info.Exists) continue; if (IsDocumentOpen(info.FullName)) { FindDocument(info.FullName).DockContent.Activate(); } else { var isOpened = false; IMyGenDocument mygenDoc = EditorManager.OpenDocument(this, info.FullName); if (mygenDoc != null) { isOpened = true; mygenDoc.DockContent.Show(MainDockPanel); AddRecentFile(info.FullName); } if (!isOpened) { MessageBox.Show(this, info.Name + ": unknown file type", "Unknown file type"); } } } } private IDockContent GetContentFromPersistString(string persistString) { IDockContent content = null; string[] parsedStrings = persistString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parsedStrings.Length == 1) { string type = parsedStrings[0]; if (type == typeof(LanguageMappings).ToString()) { content = LanguageMappingsDockContent; } else if (type == typeof(DbTargetMappings).ToString()) { content = DbTargetMappingsDockContent; } else if (type == typeof(MetaProperties).ToString()) { content = MetaPropertiesDockContent; } else if (type == typeof(MetaDataBrowser).ToString()) { content = MetaDataBrowserDockContent; } else if (type == typeof(UserMetaData).ToString()) { content = UserMetaDataDockContent; } else if (type == typeof(GlobalUserMetaData).ToString()) { content = GlobalUserMetaDataDockContent; } else if (type == typeof(TemplateBrowser).ToString()) { content = TemplateBrowserDockContent; } else if (type == typeof(DefaultSettingsDialog).ToString() && DefaultSettings.Instance.EnableDocumentStyleSettings) { content = DefaultSettingsDialog; } else if (type == typeof(ErrorsForm).ToString()) { content = ErrorsDockContent; } else if (type == typeof(GeneratedFilesForm).ToString()) { content = GeneratedFilesDockContent; } else if (type == typeof(ConsoleForm).ToString()) { content = ConsoleDockContent; } else { // Preload all dynamicContentWindows here if needed foreach (IContentManager cm in PluginManager.ContentManagers.Values) { _dynamicContentWindows[cm.Name] = cm.Create(this); } foreach (IMyGenContent c in _dynamicContentWindows.Values) { if (type == c.GetType().ToString()) { content = c.DockContent; break; } } } } else if (parsedStrings.Length >= 2) { string type = parsedStrings[0]; string arg = parsedStrings[1]; IMyGenDocument doc; if (string.Equals(type, "file", StringComparison.CurrentCultureIgnoreCase)) { doc = EditorManager.OpenDocument(this, arg); if (doc != null) content = doc.DockContent; } if (string.Equals(type, "type", StringComparison.CurrentCultureIgnoreCase)) { doc = EditorManager.CreateDocument(this, arg); if (doc != null) content = doc.DockContent; } } return content; } private bool Shutdown(bool allowPrevent) { var shutdown = true; try { string dockConfigFileName = _startupPath + DOCK_CONFIG_FILE; IMyGenContent mygenContent = null; DockContentCollection dockContentCollection = MainDockPanel.Contents; var canClose = true; if (allowPrevent && !ZeusProcessManager.IsDormant) { return false; } foreach (IDockContent dockContent in dockContentCollection) { mygenContent = dockContent as IMyGenContent; // We need the MetaDataBrowser window to be closed last // because it houses the UserMetaData if (!(mygenContent is MetaDataBrowser)) { canClose = mygenContent.CanClose(allowPrevent); if (allowPrevent && !canClose) { shutdown = false; break; } } if (dockContent.DockHandler.IsHidden) { dockContent.DockHandler.Close(); } } if (shutdown) { MainDockPanel.SaveAsXml(dockConfigFileName); } } catch { shutdown = true; } return shutdown; } #region Drag n' Drop private void MyGenerationMDI_DragDrop(object sender, DragEventArgs e) { string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop); OpenDocuments(filenames); } private void MyGenerationMDI_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, false)) { bool foundValidFile = false; string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string filename in filenames) { int idx = filename.LastIndexOf('.'); if (idx >= 0) { string ext = filename.Substring(idx + 1); foreach (IEditorManager em in PluginManager.EditorManagers.Values) { if (em.FileExtensions.ContainsKey(ext)) { foundValidFile = true; break; } } } if (foundValidFile) break; } // allow them to continue // (without this, the cursor stays a "NO" symbol if (foundValidFile) { e.Effect = DragDropEffects.All; } } } #endregion #region DockManager Helper Methods public bool IsDocumentOpen(string text, params IMyGenDocument[] docsToExclude) { IMyGenDocument doc = FindDocument(text, docsToExclude); return (doc != null); } public IMyGenDocument FindDocument(string text, params IMyGenDocument[] docsToExclude) { IMyGenDocument found = null; if (MainDockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) { if (form is IMyGenDocument) { IMyGenDocument doc = form as IMyGenDocument; if (doc.DocumentIndentity == text) { foreach (IMyGenDocument exclude in docsToExclude) { if (exclude == doc) doc = null; } if (doc != null) { found = doc; break; } } } } } else { foreach (IDockContent content in MainDockPanel.Documents) { if (content is IMyGenDocument) { IMyGenDocument doc = content as IMyGenDocument; if (doc.DocumentIndentity == text) { foreach (IMyGenDocument exclude in docsToExclude) { if (exclude == doc) doc = null; } if (doc != null) { found = doc; break; } } } } } return found; } #endregion private void dockPanel_ActiveContentChanged(object sender, EventArgs e) { IDockContent activeContent = MainDockPanel.ActiveContent; if (activeContent is IEditControl) { ToolStripManager.RevertMerge(toolStrip1); } else if (activeContent is IMyGenDocument) { ToolStripManager.RevertMerge(toolStrip1); var mgd = activeContent as IMyGenDocument; if (mgd.ToolStrip != null) { ToolStripManager.Merge(mgd.ToolStrip, toolStrip1); } } else if (activeContent == null) { var foundDoc = MainDockPanel.Contents.Cast<DockContent>().Any(c => c is IMyGenDocument && !c.IsHidden); if (!foundDoc) ToolStripManager.RevertMerge(toolStrip1); } } private int _indexImgAnimate = -1; private void timerImgAnimate_Tick(object sender, EventArgs e) { _indexImgAnimate = _indexImgAnimate >= 3 ? 0 : _indexImgAnimate + 1; switch (_indexImgAnimate) { case 0: toolStripStatusQueue.Image = Zeus.SharedResources.Refresh16x16_1; break; case 1: toolStripStatusQueue.Image = Zeus.SharedResources.Refresh16x16_2; break; case 2: toolStripStatusQueue.Image = Zeus.SharedResources.Refresh16x16_3; break; case 3: toolStripStatusQueue.Image = Zeus.SharedResources.Refresh16x16_4; break; } toolStripStatusQueue.Invalidate(); } #region Menu Event Handlers private void openToolStripMenuItem_Click(object sender, EventArgs e) { PickFiles(); } private void newFileDynamicToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem i = sender as ToolStripMenuItem; CreateDocument(i.Text); } private void openContentDynamicToolStripMenuItem_Click(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if ((Type) toolStripItem.Tag == typeof(IContentManager)) { OpenContent(string.IsNullOrEmpty(toolStripItem.Text) ? toolStripItem.ToolTipText : toolStripItem.Text); } else { ExecuteSimplePlugin(string.IsNullOrEmpty(toolStripItem.Text) ? toolStripItem.ToolTipText : toolStripItem.Text); } } private void ExitMenuItem_OnClicked(object sender, EventArgs e) { Close(); } private void AboutMenuItem_OnClicked(object sender, EventArgs e) { new AboutBox().ShowDialog(this); } private void SettingsMenuItem_OnClicked(object sender, EventArgs e) { if (!DefaultSettings.Instance.EnableDocumentStyleSettings) { if (_defaultSettingsDialog != null) { DefaultSettingsDialog.Hide(); _defaultSettingsDialog = null; } var defaultProperties = new DefaultSettingsDialog(this); defaultProperties.ShowDialog(this); } else { if (DefaultSettingsDialog.IsHidden) { DefaultSettingsDialog.Show(MainDockPanel); } else { DefaultSettingsDialog.Activate(); } } } private void HelpMenuItem_OnClicked(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; if (item != null) { Zeus.WindowsTools.LaunchHelpFile(_startupPath + item.Tag, ProcessWindowStyle.Maximized, createNoWindow: true); } } private void RecentFileMenuItem_OnClicked(object sender, EventArgs e) { if (!(sender is ToolStripMenuItem)) return; var item = sender as ToolStripMenuItem; var file = item.Text; if (File.Exists(file)) { AddRecentFile(item.Text); OpenDocuments(item.Text); } else { MessageBox.Show(this, item.Text + " no longer exists.", "File Missing"); RemoveRecentFile(item.Text); } } private void CheckForUpdateMenuItem_OnClicked(object sender, EventArgs e) { new ApplicationReleases().ShowDialog(this); } private void DocMenuItem_OnClicked(object sender, EventArgs e) { var i = sender as ToolStripMenuItem; if (i != null) { IMyGenDocument mgd = FindDocument(i.Tag.ToString()); mgd.DockContent.Activate(); } } private void WindowMenu_OnDropDownOpening(object sender, EventArgs e) { windowToolStripMenuItem.DropDownItems.Clear(); foreach (var dockContent in MainDockPanel.Contents) { var doc = (DockContent) dockContent; if (!(doc is IMyGenDocument)) continue; var mgd = doc as IMyGenDocument; if (doc.IsHidden) continue; var toolStripMenuItem = new ToolStripMenuItem(doc.Text, null, DocMenuItem_OnClicked) {Tag = mgd.DocumentIndentity}; if (doc.IsActivated) toolStripMenuItem.Checked = true; windowToolStripMenuItem.DropDownItems.Add(toolStripMenuItem); } } #endregion #region Toolstrip Button Event Handlers private void ToolStripOpenButton_OnClicked(object sender, EventArgs e) { PickFiles(); } private void ToolStripTemplateBrowserButton_OnClicked(object sender, EventArgs e) { if (TemplateBrowserDockContent.IsHidden) { TemplateBrowserDockContent.Show(MainDockPanel); } else { TemplateBrowserDockContent.Activate(); } } private void ToolStripSettingsButton_OnClicked(object sender, EventArgs e) { if (!DefaultSettings.Instance.EnableDocumentStyleSettings) { if (_defaultSettingsDialog != null) { DefaultSettingsDialog.Hide(); _defaultSettingsDialog = null; } var dsd = new DefaultSettingsDialog(this); dsd.ShowDialog(this); } else { if (DefaultSettingsDialog.IsHidden) { DefaultSettingsDialog.Show(MainDockPanel); } else { DefaultSettingsDialog.Hide(); } } } private void ToolStripMetaBrowserButton_OnClicked(object sender, EventArgs e) { if (MetaDataBrowserDockContent.IsHidden) { MetaDataBrowserDockContent.Show(MainDockPanel); } else { MetaDataBrowserDockContent.Activate(); } } private void ToolStripMyMetaPropertiesButton_OnClicked(object sender, EventArgs e) { if (MetaPropertiesDockContent.IsHidden) { MetaPropertiesDockContent.Show(MainDockPanel); } else { MetaPropertiesDockContent.Activate(); } } private void ToolStripLanguageMappingsButton_OnClicked(object sender, EventArgs e) { if (LanguageMappingsDockContent.IsHidden) { LanguageMappingsDockContent.Show(MainDockPanel); } else { LanguageMappingsDockContent.Activate(); } } private void ToolStripDbTargetMappingsButton_OnClicked(object sender, EventArgs e) { if (DbTargetMappingsDockContent.IsHidden) { DbTargetMappingsDockContent.Show(MainDockPanel); } else { DbTargetMappingsDockContent.Activate(); } } private void ToolStripLocalAliasesButton_OnClicked(object sender, EventArgs e) { if (UserMetaDataDockContent.IsHidden) { UserMetaDataDockContent.Show(MainDockPanel); } else { UserMetaDataDockContent.Activate(); } } private void ToolStripGlobalAliasesButton_OnClicked(object sender, EventArgs e) { if (GlobalUserMetaDataDockContent.IsHidden) { GlobalUserMetaDataDockContent.Show(MainDockPanel); } else { GlobalUserMetaDataDockContent.Activate(); } } private void ToolStripConsoleButton_OnClicked(object sender, EventArgs e) { if (ConsoleDockContent.IsHidden) { ConsoleDockContent.Show(MainDockPanel); } else { ConsoleDockContent.Activate(); } } private void ToolStripErrorButton_OnClicked(object sender, EventArgs e) { if (ErrorsDockContent.IsHidden) { ErrorsDockContent.Show(MainDockPanel); } else { ErrorsDockContent.Activate(); } } private void ToolStripRecentlyGeneratedFilesButton_OnClicked(object sender, EventArgs e) { if (GeneratedFilesDockContent.IsHidden) { GeneratedFilesDockContent.Show(MainDockPanel); } else { GeneratedFilesDockContent.Activate(); } } private void ToolStripOpenGeneratedOutputFolderButton_OnClicked(object sender, EventArgs e) { Process p = new Process(); p.StartInfo.FileName = "explorer"; p.StartInfo.Arguments = "/e," + DefaultSettings.Instance.DefaultOutputDirectory; p.StartInfo.UseShellExecute = true; p.Start(); } #endregion #region Lazy Load Windows public GeneratedFilesForm GeneratedFilesDockContent { get { if ((_generatedFilesForm != null) && _generatedFilesForm.IsDisposed) _generatedFilesForm = null; if (_generatedFilesForm == null) _generatedFilesForm = new GeneratedFilesForm(this); return _generatedFilesForm; } } public ConsoleForm ConsoleDockContent { get { if ((_consoleForm != null) && _consoleForm.IsDisposed) _consoleForm = null; if (_consoleForm == null) _consoleForm = new ConsoleForm(this); return _consoleForm; } } public ErrorsForm ErrorsDockContent { get { if ((_errorsForm != null) && _errorsForm.IsDisposed) _errorsForm = null; if (_errorsForm == null) _errorsForm = new ErrorsForm(this); return _errorsForm; } } public ErrorDetail ErrorDetailDockContent { get { if ((_errorDetail != null) && _errorDetail.IsDisposed) _errorDetail = null; if (_errorDetail == null) _errorDetail = new ErrorDetail(this); return _errorDetail; } } public DefaultSettingsDialog DefaultSettingsDialog { get { if (_defaultSettingsDialog != null && _defaultSettingsDialog.IsDisposed) _defaultSettingsDialog = null; return _defaultSettingsDialog ?? (_defaultSettingsDialog = new DefaultSettingsDialog(this)); } } public TemplateBrowser TemplateBrowserDockContent { get { if ((_templateBrowser != null) && _templateBrowser.IsDisposed) _templateBrowser = null; if (_templateBrowser == null) _templateBrowser = new TemplateBrowser(this); return _templateBrowser; } } public LanguageMappings LanguageMappingsDockContent { get { if ((_languageMappings != null) && _languageMappings.IsDisposed) _languageMappings = null; if (_languageMappings == null) _languageMappings = new LanguageMappings(this); return _languageMappings; } } public DbTargetMappings DbTargetMappingsDockContent { get { if ((_dbTargetMappings != null) && _dbTargetMappings.IsDisposed) _dbTargetMappings = null; if (_dbTargetMappings == null) _dbTargetMappings = new DbTargetMappings(this); return _dbTargetMappings; } } public MetaDataBrowser MetaDataBrowserDockContent { get { if ((_metaDataBrowser != null) && _metaDataBrowser.IsDisposed) _metaDataBrowser = null; if (_metaDataBrowser == null) _metaDataBrowser = new MetaDataBrowser(this, MetaPropertiesDockContent, UserMetaDataDockContent, GlobalUserMetaDataDockContent); return _metaDataBrowser; } } public UserMetaData UserMetaDataDockContent { get { if ((_userMetaData != null) && _userMetaData.IsDisposed) _userMetaData = null; if (_userMetaData == null) { _userMetaData = new UserMetaData(this); _userMetaData.MetaDataBrowser = MetaDataBrowserDockContent; } return _userMetaData; } } public GlobalUserMetaData GlobalUserMetaDataDockContent { get { if ((_globalUserMetaData != null) && _globalUserMetaData.IsDisposed) _globalUserMetaData = null; if (_globalUserMetaData == null) { _globalUserMetaData = new GlobalUserMetaData(this); _globalUserMetaData.MetaDataBrowser = MetaDataBrowserDockContent; } return _globalUserMetaData; } } public MetaProperties MetaPropertiesDockContent { get { if ((_metaProperties != null) && _metaProperties.IsDisposed) _metaProperties = null; if (_metaProperties == null) _metaProperties = new MetaProperties(this); return _metaProperties; } } #endregion private void ProcessReplacementFiles() { var dir = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath)); foreach (FileInfo info in dir.GetFiles("*" + REPLACEMENT_SUFFIX)) { var fileToReplace = new FileInfo(info.FullName.Replace(REPLACEMENT_SUFFIX, ".dll")); try { if (fileToReplace.Exists) { fileToReplace.MoveTo(fileToReplace.FullName + "." + DateTime.Now.ToString("yyyyMMddhhmmss") + ".bak"); } info.MoveTo(fileToReplace.FullName); } catch { } } } #region Refresh Recent Files private void RefreshRecentFiles() { recentFilesToolStripMenuItem.DropDownItems.Clear(); DefaultSettings ds = DefaultSettings.Instance; if (ds.RecentFiles.Count == 0) { recentFilesToolStripMenuItem.Visible = false; } else { recentFilesToolStripMenuItem.Visible = true; foreach (string path in ds.RecentFiles) { var item = new ToolStripMenuItem(path); item.Click += RecentFileMenuItem_OnClicked; recentFilesToolStripMenuItem.DropDownItems.Add(item); } } } private void AddRecentFile(string path) { if (DefaultSettings.Instance.RecentFiles.Contains(path)) { DefaultSettings.Instance.RecentFiles.Remove(path); } DefaultSettings.Instance.RecentFiles.Insert(0, path); DefaultSettings.Instance.Save(); RefreshRecentFiles(); } private void RemoveRecentFile(string path) { if (DefaultSettings.Instance.RecentFiles.Contains(path)) { DefaultSettings.Instance.RecentFiles.Remove(path); } DefaultSettings.Instance.Save(); RefreshRecentFiles(); } #endregion #region Show OLEDBDialog Dialog protected string BrowseOleDbConnectionString(string connstr) { var dl = new MSDASC.DataLinksClass {hWnd = Handle.ToInt32()}; var conn = new ADODB.Connection {ConnectionString = connstr}; object objCn = conn; return dl.PromptEdit(ref objCn) ? conn.ConnectionString : null; } #endregion #region IMyGenerationMDI Members public IZeusController ZeusController { get { return Zeus.ZeusController.Instance; } } private readonly FindForm _findForm = new FindForm(); public FindForm FindDialog { get { return _findForm; } } private readonly ReplaceForm _replaceForm = new ReplaceForm(); public ReplaceForm ReplaceDialog { get { return _replaceForm; } } public ScintillaConfigureDelegate ConfigureDelegate { get { return _scintillaConfigureDelegate; } } public DockPanel DockPanel { get { return MainDockPanel; } } public void SendAlert(IMyGenContent sender, string command, params object[] args) { IMyGenContent contentItem = null; DockContentCollection contents = MainDockPanel.Contents; DefaultSettings settings = DefaultSettings.Instance; for (int i = 0; i < contents.Count; i++) { contentItem = contents[i] as IMyGenContent; if (contentItem != null) { contentItem.ProcessAlert(sender, command, args); } } } public object PerformMdiFunction(IMyGenContent sender, string function, params object[] args) { if (function.Equals("getstaticdbroot", StringComparison.CurrentCultureIgnoreCase)) { return MetaDataBrowser.StaticMyMetaObj; } if (function.Equals("showoledbdialog", StringComparison.CurrentCultureIgnoreCase) && args.Length == 1) { return BrowseOleDbConnectionString(args[0].ToString()); } if (function.Equals("executionqueuestart", StringComparison.CurrentCultureIgnoreCase)) { toolStripStatusQueue.Visible = true; timerImgAnimate.Start(); } else if (function.Equals("executionqueueupdate", StringComparison.CurrentCultureIgnoreCase)) { if (ZeusProcessManager.ProcessCount == 0) { timerImgAnimate.Stop(); toolStripStatusQueue.Visible = false; } else if (ZeusProcessManager.ProcessCount > 0) { toolStripStatusQueue.Visible = true; timerImgAnimate.Start(); } } else if (function.Equals("showerrordetail", StringComparison.CurrentCultureIgnoreCase) && args.Length >= 1) { if (args[0] is List<IMyGenError>) { List<IMyGenError> errors = args[0] as List<IMyGenError>; ErrorDetailDockContent.Update(errors[0]); if (ErrorDetailDockContent.IsHidden) { ErrorDetailDockContent.Show(MainDockPanel); } else { ErrorDetailDockContent.Activate(); } } } else if (function.Equals("navigatetotemplateerror", StringComparison.CurrentCultureIgnoreCase) && args.Length >= 1) { if (args[0] is IMyGenError) { IMyGenError error = args[0] as IMyGenError; TemplateEditor edit = null; if (string.IsNullOrEmpty(error.SourceFile)) { //it's a new unsaved template bool isopen = IsDocumentOpen(error.TemplateIdentifier); if (isopen) { edit = FindDocument(error.TemplateIdentifier) as TemplateEditor; edit.Activate(); } } else { FileInfo file = new FileInfo(error.TemplateFileName); if (file.Exists) { bool isopen = IsDocumentOpen(file.FullName); if (!isopen) { edit = new TemplateEditor(this); edit.FileOpen(file.FullName); } else { edit = FindDocument(file.FullName) as TemplateEditor; if (edit != null) { edit.Activate(); } } } } if (edit != null) { edit.NavigateTo(error); } } } else if (function.Equals("getmymetadbdriver", StringComparison.CurrentCultureIgnoreCase)) { return DefaultSettings.Instance.DbDriver; } else if (function.Equals("getmymetaconnection", StringComparison.CurrentCultureIgnoreCase)) { return DefaultSettings.Instance.ConnectionString; } else if (function.Equals("openfile", StringComparison.CurrentCultureIgnoreCase) && args.Length == 1) { if (args[0] is List<FileInfo>) { List<FileInfo> files = args[0] as List<FileInfo>; foreach (FileInfo fi in files) { Zeus.WindowsTools.LaunchFile(fi.FullName); } } else if (args[0] is FileInfo) { FileInfo file = args[0] as FileInfo; Zeus.WindowsTools.LaunchFile(file.FullName); } else if (args[0] is String) { Zeus.WindowsTools.LaunchFile(args[0].ToString()); } } return null; } public IMyGenConsole Console { get { return ConsoleDockContent; } } public IMyGenErrorList ErrorList { get { return ErrorsDockContent; } } public void WriteConsole(string text, params object[] args) { ConsoleDockContent.Write(text, args); } public void ErrorsOccurred(params Exception[] exs) { ErrorsDockContent.AddErrors(exs); foreach (Exception ex in exs) ConsoleDockContent.Write(ex); } #endregion #region Error Handling public void UnhandledExceptions(object sender, UnhandledExceptionEventArgs args) { try { // Most likey the application is terminating on this method Exception ex = (Exception)args.ExceptionObject; HandleError(ex); } catch { } } public void OnThreadException(object sender, ThreadExceptionEventArgs t) { try { Exception ex = t.Exception; HandleError(ex); } catch { } } private void HandleError(Exception ex) { try { if (ErrorsDockContent != null) { ErrorsDockContent.AddErrors(ex); } if (ConsoleDockContent != null) { ConsoleDockContent.Write(ex); } } catch { } } #endregion } }
#region License // Copyright 2015 Kastellanos Nikolaos // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; namespace tainicom.Devices { public class InputState { #region Fields // Touch private TouchLocation _mouseTouchLocation; private TouchLocation _prevMouseTouchLocation; public bool IsGestureAvailable; private TouchCollection _touchCollection; private List<GestureSample> _gestures = new List<GestureSample>(4); // GamePad (... and Back button on phones) private GamePadState _prevGamePadState; private GamePadState _gamePadState; // Keyboard private KeyboardState _prevKeyboardState; private KeyboardState _keyboardState; // Mouse private MouseState _prevMouseState; private MouseState _mouseState; #endregion /// <summary> /// Emulate touch input with mouse /// </summary> public bool EmulateTouch { get;set; } private DateTime _pressTimestamp; #region Properties public TouchCollection TouchCollection { get { return _touchCollection; } } public List<GestureSample> Gestures { get { return _gestures; } } public GamePadState GamePadState { get { return _gamePadState; } } public GamePadState PrevGamePadState { get { return _prevGamePadState; } } public KeyboardState KeyboardState { get { return _keyboardState; } } public KeyboardState PrevKeyboardState { get { return _prevKeyboardState; } } public MouseState MouseState { get { return _mouseState; } } public MouseState PrevMouseState { get { return _prevMouseState; } } #endregion #region Initialization public InputState() { EmulateTouch = true; } #endregion /// <param name="isActive">The value of Game.IsActive</param> public void Update(bool isActive) { _prevGamePadState = _gamePadState; _gamePadState = GamePad.GetState(PlayerIndex.One); _prevKeyboardState = _keyboardState; _keyboardState = Keyboard.GetState(); _touchCollection = TouchPanel.GetState(); IsGestureAvailable = false; if(TouchPanel.EnabledGestures != GestureType.None) { IsGestureAvailable = TouchPanel.IsGestureAvailable; _gestures.Clear(); while (TouchPanel.IsGestureAvailable) { _gestures.Add(TouchPanel.ReadGesture()); } } #if (!WP7) // Ignore mouse state from Windows Phone 7. It will emulate Mouse from Primary Touch location. _prevMouseState = _mouseState; _mouseState = Mouse.GetState(); #endif if (EmulateTouch) { EmulateStateWithMouse(isActive); EmulateGesturesWithMouse(isActive); } return; } private void EmulateStateWithMouse(bool isActive) { Vector2 position = new Vector2(_mouseState.X, _mouseState.Y); _prevMouseTouchLocation = _mouseTouchLocation; if (isActive ) { //pressed if (_mouseState.LeftButton == ButtonState.Pressed && _prevMouseState.LeftButton == ButtonState.Released) { _mouseTouchLocation = new TouchLocation(10000, TouchLocationState.Pressed, position); } //moved if (_mouseState.LeftButton == ButtonState.Pressed && _prevMouseState.LeftButton == ButtonState.Pressed) { _mouseTouchLocation = new TouchLocation(_mouseTouchLocation.Id, TouchLocationState.Moved, position, _mouseTouchLocation.State, _mouseTouchLocation.Position); } // if (_mouseState.LeftButton == ButtonState.Released && _prevMouseState.LeftButton == ButtonState.Pressed) { _mouseTouchLocation = new TouchLocation(_mouseTouchLocation.Id, TouchLocationState.Released, position, _mouseTouchLocation.State, _mouseTouchLocation.Position); } if (_mouseState.LeftButton == ButtonState.Released && _prevMouseState.LeftButton == ButtonState.Released) { _mouseTouchLocation = new TouchLocation(); } } else { if (_prevMouseState.LeftButton == ButtonState.Pressed) { _mouseTouchLocation = new TouchLocation(_mouseTouchLocation.Id, TouchLocationState.Released, position, _mouseTouchLocation.State, _mouseTouchLocation.Position); } } //replace touchCollection if (_mouseTouchLocation.State != TouchLocationState.Invalid) { TouchLocation[] touchLocationArray = new TouchLocation[_touchCollection.Count + 1]; _touchCollection.CopyTo(touchLocationArray, 0); touchLocationArray[touchLocationArray.Length - 1] = _mouseTouchLocation; _touchCollection = new TouchCollection(touchLocationArray); } return; } // this is a very basic emulation of touch. // Tap, Hold, Moved, HorizontalDrag, FreeDrag, DragComplete private void EmulateGesturesWithMouse(bool isActive) { if (!isActive) return; if (TouchPanel.EnabledGestures == GestureType.None) return; if (_mouseTouchLocation.State == TouchLocationState.Invalid) return; //if (mouseTouchLocation.Position.X < 0 || mouseTouchLocation.Position.Y < 0 || // mouseTouchLocation.Position.X >= TouchPanel.DisplayWidth || // mouseTouchLocation.Position.Y >= TouchPanel.DisplayHeight) return; Vector2 delta = _mouseTouchLocation.Position-_prevMouseTouchLocation.Position; bool pressing = _mouseTouchLocation.State == TouchLocationState.Pressed && (_prevMouseTouchLocation.State == TouchLocationState.Released || _prevMouseTouchLocation.State == TouchLocationState.Invalid); bool pressed = _mouseTouchLocation.State == TouchLocationState.Moved && (_prevMouseTouchLocation.State == TouchLocationState.Pressed || _prevMouseTouchLocation.State == TouchLocationState.Moved); bool releasing = _mouseTouchLocation.State == TouchLocationState.Released && (_prevMouseTouchLocation.State == TouchLocationState.Pressed || _prevMouseTouchLocation.State == TouchLocationState.Moved); bool released = _mouseTouchLocation.State == TouchLocationState.Released && (_prevMouseTouchLocation.State == TouchLocationState.Released || _prevMouseTouchLocation.State == TouchLocationState.Invalid); if(pressing) _pressTimestamp = DateTime.Now; TimeSpan pressDuration = (DateTime.Now-_pressTimestamp); /* if (mouseTouchLocation.State == TouchLocationState.Pressed) { if (TouchPanel.EnabledGestures == GestureType.Tap) { //if only tap was expected, return now gestures.Add(new GestureSample(GestureType.Tap,TimeSpan.Zero, mouseTouchLocation.Position,Vector2.Zero, Vector2.Zero,Vector2.Zero)); IsGestureAvailable = true; } } */ TimeSpan maxTapDuration = TimeSpan.FromMilliseconds(600); if (releasing) { if ((TouchPanel.EnabledGestures & GestureType.Tap) != GestureType.None && delta == Vector2.Zero && pressDuration < maxTapDuration) { _gestures.Add(new GestureSample(GestureType.Tap, TimeSpan.Zero, _mouseTouchLocation.Position, Vector2.Zero, Vector2.Zero, Vector2.Zero)); IsGestureAvailable = true; } } if (_mouseTouchLocation.State == TouchLocationState.Moved && _prevMouseTouchLocation.State == TouchLocationState.Moved) { if ((TouchPanel.EnabledGestures & GestureType.Hold) != GestureType.None && delta == Vector2.Zero) { _gestures.Add(new GestureSample(GestureType.Hold, TimeSpan.Zero, _mouseTouchLocation.Position, Vector2.Zero, Vector2.Zero, Vector2.Zero)); IsGestureAvailable = true; } } if (_mouseTouchLocation.State == TouchLocationState.Moved) { if ((TouchPanel.EnabledGestures & GestureType.HorizontalDrag) != GestureType.None && delta.X != 0) { _gestures.Add(new GestureSample(GestureType.HorizontalDrag, TimeSpan.Zero, _mouseTouchLocation.Position, Vector2.Zero, delta, Vector2.Zero)); IsGestureAvailable = true; } if ((TouchPanel.EnabledGestures & GestureType.FreeDrag) != GestureType.None && delta != Vector2.Zero) { _gestures.Add(new GestureSample(GestureType.FreeDrag, TimeSpan.Zero, _mouseTouchLocation.Position, Vector2.Zero, delta, Vector2.Zero)); IsGestureAvailable = true; } } if (_mouseTouchLocation.State == TouchLocationState.Released && _prevMouseTouchLocation.State == TouchLocationState.Moved) { if ((TouchPanel.EnabledGestures & GestureType.DragComplete) != GestureType.None) { _gestures.Add(new GestureSample(GestureType.DragComplete, TimeSpan.Zero, _mouseTouchLocation.Position, Vector2.Zero, Vector2.Zero, Vector2.Zero)); IsGestureAvailable = true; } } return; } public bool IsButtonPressed(Buttons button) { return (_gamePadState.IsButtonDown(button) && _prevGamePadState.IsButtonUp(button)); } public bool IsButtonReleased(Buttons button) { return (_gamePadState.IsButtonUp(button) && _prevGamePadState.IsButtonDown(button)); } public bool IsButtonUp(Buttons button) { return (_gamePadState.IsButtonUp(button) && _prevGamePadState.IsButtonUp(button)); } public bool IsButtonDown(Buttons button) { return (_gamePadState.IsButtonDown(button) && _prevGamePadState.IsButtonDown(button)); } public bool IsKeyPressed(Keys key) { return (_keyboardState.IsKeyDown(key) && _prevKeyboardState.IsKeyUp(key)); } public bool IsKeyReleased(Keys key) { return (_keyboardState.IsKeyUp(key) && _prevKeyboardState.IsKeyDown(key)); } public bool IsKeyUp(Keys key) { return (_keyboardState.IsKeyUp(key) && _prevKeyboardState.IsKeyUp(key)); } public bool IsKeyDown(Keys key) { return (_keyboardState.IsKeyDown(key) && _prevKeyboardState.IsKeyDown(key)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; namespace Keen.Core { /// <summary> /// An implementation of <see cref="IHttpClientProvider"/> that caches HttpClient instances in /// a dictionary mapping the base URL to a WeakReference to the actual instance. A PRO to this /// approach is that HttpClient instances will automatically be evicted when no more strong /// refs exist and the GC collects. A CON to using WeakReference, besides it not being generic /// in the current version of the PCL and being a fairly heavyweight class, is that rapid /// creation and releasing of owning instances like the KeenClient can still allow for the GC /// to aggressively clean up HttpClient instances. Recommended usage of KeenClient shouldn't /// make this a common problem, but at some point this cache can evolve to be more intelligent /// about keeping instances alive deliberately. /// </summary> internal class HttpClientCache : IHttpClientProvider { // A singleton cache that can optionally be used and shared. If new caches need to be // created, use the internal ctor. One use case for this might be to have multiple // HttpClient instances with different configurations cached for the same URL for use in // different sets of client modules. internal static HttpClientCache Instance { get; } = new HttpClientCache(); // Explicit static constructor, no beforefieldinit static HttpClientCache() { } private readonly object _cacheLock; // NOTE : We should use ConcurrentDictionary<Uri, Lazy<>> here. if/when we upgrade the PCL // profile to something >= .NET 4.0. // NOTE : Use WeakReference<T> in 4.5+ private readonly IDictionary<Uri, WeakReference> _httpClients; // No external construction internal HttpClientCache() { _cacheLock = new object(); _httpClients = new Dictionary<Uri, WeakReference>(); } /// <summary> /// Retrieve an existing HttpClient for the given URL, or throw if it doesn't exist. /// </summary> /// <param name="baseUrl">The base URL the HttpClient is tied to.</param> /// <returns>The HttpClient which is expected to exist.</returns> public HttpClient this[Uri baseUrl] { get { HttpClient httpClient = null; lock (_cacheLock) { WeakReference weakRef = null; if (!_httpClients.TryGetValue(baseUrl, out weakRef)) { throw new KeenException( string.Format("No existing HttpClient for baseUrl \"{0}\"", baseUrl)); } httpClient = weakRef.Target as HttpClient; if (null == httpClient) { throw new KeenException( string.Format("Existing HttpClient for baseUrl \"{0}\" has been" + "garbage collected.", baseUrl)); } } return httpClient; } } /// <summary> /// Retrieve an existing HttpClient for the given URL, or create one with the given /// handlers and headers. /// </summary> /// <param name="baseUrl">The base URL the HttpClient is tied to.</param> /// <param name="getHandlerChain">A factory function to create a handler chain.</param> /// <param name="defaultHeaders">Any headers that all requests to this URL should add by /// default.</param> /// <returns>An HttpClient configured to handle requests for the given URL.</returns> public HttpClient GetOrCreateForUrl( Uri baseUrl, Func<HttpMessageHandler> getHandlerChain = null, IEnumerable<KeyValuePair<string, string>> defaultHeaders = null) { Action<HttpClient> configure = null; if (null != defaultHeaders && Enumerable.Any(defaultHeaders)) { configure = (httpClientToConfigure) => { foreach (var header in defaultHeaders) { httpClientToConfigure.DefaultRequestHeaders.Add(header.Key, header.Value); } }; } HttpClient httpClient = GetOrCreateForUrl(baseUrl, getHandlerChain, configure); return httpClient; } /// <summary> /// Retrieve an existing HttpClient for the given URL, or create one with the given /// handlers and configuration functor. /// </summary> /// <param name="baseUrl">The base URL the HttpClient is tied to.</param> /// <param name="getHandlerChain">A factory function to create a handler chain.</param> /// <param name="configure">An action that takes the newly created HttpClient and /// configures it however needed before it is stored and/or returned.</param> /// <returns>An HttpClient configured to handle requests for the given URL.</returns> public HttpClient GetOrCreateForUrl( Uri baseUrl, Func<HttpMessageHandler> getHandlerChain = null, Action<HttpClient> configure = null) { if (null == baseUrl) { throw new ArgumentNullException(nameof(baseUrl), string.Format("Cannot use a null {0} as a key.", nameof(baseUrl))); } HttpClient httpClient = null; lock (_cacheLock) { WeakReference weakRef = null; if (!_httpClients.TryGetValue(baseUrl, out weakRef) || null == (httpClient = weakRef.Target as HttpClient)) { // If no handler chain is provided, a plain HttpClientHandler with no // configuration whatsoever is installed. httpClient = new HttpClient(getHandlerChain?.Invoke() ?? new HttpClientHandler()); httpClient.BaseAddress = baseUrl; configure?.Invoke(httpClient); // Reuse the WeakReference if we already had an entry for this url. if (null == weakRef) { _httpClients[baseUrl] = new WeakReference(httpClient); } else { weakRef.Target = httpClient; } } } return httpClient; } /// <summary> /// Remove any cached HttpClients associated with the given URL. /// </summary> /// <param name="baseUrl">The base URL for which any cached HttpClient instances should /// be purged.</param> public void RemoveForUrl(Uri baseUrl) { if (null == baseUrl) { throw new ArgumentNullException(nameof(baseUrl), string.Format("Cannot use a null {0} as a key.", nameof(baseUrl))); } lock (_cacheLock) { _httpClients.Remove(baseUrl); } } /// <summary> /// Can this provider return an HttpClient instance for the given URL? For this /// implementation, we'll check if an entry exists in the cache and if the WeakReference /// is still valid and a strong ref can be taken. /// </summary> /// <param name="baseUrl">The base URL for which we'd like to know if an HttpClient can be /// provided.</param> /// <returns>True if this provider could return an HttpClient for the given URL, false /// otherwise.</returns> public bool ExistsForUrl(Uri baseUrl) { if (null == baseUrl) { // We can't have null keys, so we wouldn't ever be able to look up this URL. return false; } lock (_cacheLock) { WeakReference weakRef = null; bool exists = (_httpClients.TryGetValue(baseUrl, out weakRef) && (null != weakRef.Target as HttpClient)); return exists; } } /// <summary> /// Drop all HttpClient instances from the cache, no matter the URL. /// </summary> internal void Clear() { lock (_cacheLock) { _httpClients.Clear(); } } /// <summary> /// Override the HttpClient provided for a given URL. This tests and replaces or inserts /// all in one atomic operation. This will likely be useful for testing. /// </summary> /// <param name="baseUrl">URL to override.</param> /// <param name="httpClient">HttpClient instance that will do the overriding.</param> internal void OverrideForUrl(Uri baseUrl, HttpClient httpClient) { lock (_cacheLock) { WeakReference weakRef = null; if (!_httpClients.TryGetValue(baseUrl, out weakRef)) { _httpClients[baseUrl] = new WeakReference(httpClient); } else { weakRef.Target = httpClient; } } } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // Copyright (c) 2020 Upendo Ventures, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Hotcakes.Commerce; using Hotcakes.Commerce.Dnn.Utils; using Hotcakes.Commerce.Globalization; using Hotcakes.Commerce.Utilities; using Hotcakes.Modules.Core.Admin.Controls; using Hotcakes.Web; namespace Hotcakes.Modules.Core.Admin.AppCode { [Serializable] public class BaseAdminPage : Page, IHccPage { #region Fields protected const string WizardPagePath = "~/DesktopModules/Hotcakes/Core/Admin/SetupWizard/SetupWizard.aspx"; protected const string WizardPageStepPath = "~/DesktopModules/Hotcakes/Core/Admin/SetupWizard/SetupWizard.aspx?step={0}"; protected const string DefaultCatalogPage = "~/DesktopModules/Hotcakes/Core/Admin/Catalog/Default.aspx"; private readonly ArrayList _localizedControls = new ArrayList(); #endregion #region Properties public string ResourceKeyName { get { return "resourcekey"; } } private string _localResourceFile; public virtual string LocalResourceFile { get { if (string.IsNullOrEmpty(_localResourceFile)) { var index = AppRelativeVirtualPath.LastIndexOf('/'); _localResourceFile = AppRelativeVirtualPath.Insert(index + 1, "App_LocalResources/"); } return _localResourceFile; } set { _localResourceFile = value; } } public ILocalizationHelper Localization { get; set; } protected IMessageBox PageMessageBox { get; set; } public HotcakesApplication HccApp { get { return HotcakesApplication.Current; } } public string PageTitle { get { return Title; } set { Title = value; } } public AdminTabType CurrentTab { get; set; } public virtual bool ForceWizardRedirect { get { return true; } } #endregion #region Event handlers protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); // We don't care about culuture of store at this time. // We simply need some non-localizable store settings to initialize thread culture. var currentStore = HccRequestContext.Current.CurrentStore; if (ForceWizardRedirect && currentStore == null && CurrentTab != AdminTabType.SetupWizard) { Response.Redirect(WizardPagePath); } HccRequestContextUtils.UpdateAdminContentCulture(HccRequestContext.Current); // Redirect to HTTPS if ssl required if (currentStore != null) { if (currentStore.Settings.ForceAdminSSL && !Request.IsSecureConnection) SSL.SSLRedirect(SSL.SSLRedirectTo.SSL); CultureSwitch.SetCulture(currentStore); } ValidateBasicAccess(); Localization = Factory.Instance.CreateLocalizationHelper(LocalResourceFile); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); WebForms.MakePageNonCacheable(this); } protected override void Render(HtmlTextWriter writer) { IterateControls(Controls, _localizedControls, Localization); RemoveKeyAttribute(_localizedControls); base.Render(writer); } #endregion #region Implementation private void ValidateBasicAccess() { if (!HccApp.MembershipServices.IsUserLoggedIn()) { Response.Redirect(HccApp.MembershipServices.GetLoginPagePath()); } } protected bool HasCurrentUserPermission(string permission) { return HccApp.MembershipServices.HasCurrentUserPermission(permission, HccApp); } protected void ValidateCurrentUserHasPermission(string permission) { if (!HasCurrentUserPermission(permission)) { Response.Redirect(HccApp.MembershipServices.GetLoginPagePath()); } } protected void ShowMessage(string message, ErrorTypes type) { switch (type) { case ErrorTypes.Ok: PageMessageBox.ShowOk(message); break; case ErrorTypes.Info: PageMessageBox.ShowInformation(message); break; case ErrorTypes.Error: PageMessageBox.ShowError(message); break; case ErrorTypes.Warning: PageMessageBox.ShowWarning(message); break; } } protected DateTime ConvertStartDateToUtc(DateTime? date) { if (date.HasValue) return DateHelper.ConvertStoreTimeToUtc(HccApp, date.Value.ZeroOutTime()); return DateTime.UtcNow; } protected DateTime ConvertEndDateToUtc(DateTime? date) { if (date.HasValue) return DateHelper.ConvertStoreTimeToUtc(HccApp, date.Value.MaxOutTime()); return DateTime.UtcNow; } #endregion #region Localization private void IterateControls(ControlCollection controls, ArrayList affectedControls, ILocalizationHelper localization) { foreach (Control control in controls) { ProcessControl(control, affectedControls, true, localization); } } private void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, ILocalizationHelper localization) { if (!control.Visible) return; //Perform the substitution if a key was found var key = GetControlAttribute(control, affectedControls, ResourceKeyName); if (!string.IsNullOrEmpty(key)) { //Translation starts here .... var value = localization.GetString(key); if (control is Label) { var label = (Label) control; if (!string.IsNullOrEmpty(value)) { label.Text = value; } } if (control is LinkButton) { var linkButton = (LinkButton) control; if (!string.IsNullOrEmpty(value)) { var imgMatches = Regex.Matches(value, "<(a|link|img|script|input|form).[^>]*(href|src|action)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)[^>]*>", RegexOptions.IgnoreCase); foreach (Match match in imgMatches) { if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) != -1) { var resolvedUrl = Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value); value = value.Replace(match.Groups[match.Groups.Count - 2].Value, resolvedUrl); } } linkButton.Text = value; if (string.IsNullOrEmpty(linkButton.ToolTip)) { linkButton.ToolTip = value; } } } if (control is HyperLink) { var hyperLink = (HyperLink) control; if (!string.IsNullOrEmpty(value)) { hyperLink.Text = value; } } if (control is ImageButton) { var imageButton = (ImageButton) control; if (!string.IsNullOrEmpty(value)) { imageButton.AlternateText = value; } } if (control is Button) { var button = (Button) control; if (!string.IsNullOrEmpty(value)) { button.Text = value; } } if (control is HtmlInputButton) { var button = (HtmlInputButton) control; if (!string.IsNullOrEmpty(value)) { button.Value = value; } } if (control is HtmlButton) { var button = (HtmlButton) control; if (!string.IsNullOrEmpty(value)) { button.Attributes["Title"] = value; } } if (control is HtmlImage) { var htmlImage = (HtmlImage) control; if (!string.IsNullOrEmpty(value)) { htmlImage.Alt = value; } } if (control is CheckBox) { var checkBox = (CheckBox) control; if (!string.IsNullOrEmpty(value)) { checkBox.Text = value; } var toolTipValue = localization.GetString(key + ".ToolTip"); if (!string.IsNullOrEmpty(toolTipValue)) { checkBox.ToolTip = toolTipValue; } } if (control is BaseValidator) { var baseValidator = (BaseValidator) control; if (!string.IsNullOrEmpty(value)) { baseValidator.Text = value; } var errorMessageValue = localization.GetString(key + ".ErrorMessage"); if (!string.IsNullOrEmpty(errorMessageValue)) { baseValidator.ErrorMessage = errorMessageValue; } } if (control is Image) { var image = (Image) control; if (!string.IsNullOrEmpty(value)) { image.AlternateText = value; image.ToolTip = value; } } } //Translate listcontrol items here if (control is ListControl) { var listControl = (ListControl) control; for (var i = 0; i <= listControl.Items.Count - 1; i++) { var attributeCollection = listControl.Items[i].Attributes; key = attributeCollection[ResourceKeyName]; if (key != null) { var value = localization.GetString(key); if (!string.IsNullOrEmpty(value)) { listControl.Items[i].Text = value; } } if (key != null && affectedControls != null) { affectedControls.Add(attributeCollection); } } } // translate table control header cells if (control is Table) { var table = (Table) control; foreach (var row in table.Rows) { if (row is TableHeaderRow) { var thr = (TableHeaderRow) row; foreach (var cell in thr.Cells) { var thc = (TableHeaderCell) cell; var attributeCollection = thc.Attributes; key = attributeCollection[ResourceKeyName]; if (key != null) { var value = localization.GetString(key); if (!string.IsNullOrEmpty(value)) { thc.Text = value; } } } return; } } } //Process child controls if (includeChildren && control.HasControls()) { var hccUserControl = control as HccUserControl; if (hccUserControl == null) { //Pass Resource File Root through IterateControls(control.Controls, affectedControls, localization); } else { //Get Resource File Root from Controls LocalResourceFile Property IterateControls(control.Controls, affectedControls, hccUserControl.Localization); } } } private string GetControlAttribute(Control control, ArrayList affectedControls, string attributeName) { AttributeCollection attributeCollection = null; string key = null; if (!(control is LiteralControl)) { if (control is WebControl) { var webControl = (WebControl) control; attributeCollection = webControl.Attributes; key = attributeCollection[attributeName]; } else { if (control is HtmlControl) { var htmlControl = (HtmlControl) control; attributeCollection = htmlControl.Attributes; key = attributeCollection[attributeName]; } else { if (control is UserControl) { var userControl = (UserControl) control; attributeCollection = userControl.Attributes; key = attributeCollection[attributeName]; } else { var controlType = control.GetType(); var attributeProperty = controlType.GetProperty("Attributes", typeof (AttributeCollection)); if (attributeProperty != null) { attributeCollection = (AttributeCollection) attributeProperty.GetValue(control, null); key = attributeCollection[attributeName]; } } } } } if (key != null && affectedControls != null) { affectedControls.Add(attributeCollection); } return key; } private void RemoveKeyAttribute(ArrayList affectedControls) { if (affectedControls == null) { return; } int i; for (i = 0; i <= affectedControls.Count - 1; i++) { var ac = (AttributeCollection) affectedControls[i]; ac.Remove(ResourceKeyName); } } #endregion } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; using System.Collections; using NUnit.Framework.Constraints; namespace NUnit.Framework.Tests { /// <summary> /// This test fixture attempts to exercise all the syntactic /// variations of Assert without getting into failures, errors /// or corner cases. Thus, some of the tests may be duplicated /// in other fixtures. /// /// Each test performs the same operations using the classic /// syntax (if available) and the new syntax in both the /// helper-based and inherited forms. /// /// This Fixture will eventually be duplicated in other /// supported languages. /// </summary> [TestFixture] public class AssertSyntaxTests : AssertionHelper { #region Simple Constraint Tests [Test] public void IsNull() { object nada = null; // Classic syntax Assert.IsNull(nada); // Helper syntax Assert.That(nada, Is.Null); // Inherited syntax Expect(nada, Null); } [Test] public void IsNotNull() { // Classic syntax Assert.IsNotNull(42); // Helper syntax Assert.That(42, Is.Not.Null); // Inherited syntax Expect( 42, Not.Null ); } [Test] public void IsTrue() { // Classic syntax Assert.IsTrue(2+2==4); // Helper syntax Assert.That(2+2==4, Is.True); Assert.That(2+2==4); // Inherited syntax Expect(2+2==4, True); Expect(2+2==4); } [Test] public void IsFalse() { // Classic syntax Assert.IsFalse(2+2==5); // Helper syntax Assert.That(2+2== 5, Is.False); // Inherited syntax Expect(2+2==5, False); } [Test] public void IsNaN() { double d = double.NaN; float f = float.NaN; // Classic syntax Assert.IsNaN(d); Assert.IsNaN(f); // Helper syntax Assert.That(d, Is.NaN); Assert.That(f, Is.NaN); // Inherited syntax Expect(d, NaN); Expect(f, NaN); } [Test] public void EmptyStringTests() { // Classic syntax Assert.IsEmpty(""); Assert.IsNotEmpty("Hello!"); // Helper syntax Assert.That("", Is.Empty); Assert.That("Hello!", Is.Not.Empty); // Inherited syntax Expect("", Empty); Expect("Hello!", Not.Empty); } [Test] public void EmptyCollectionTests() { // Classic syntax Assert.IsEmpty(new bool[0]); Assert.IsNotEmpty(new int[] { 1, 2, 3 }); // Helper syntax Assert.That(new bool[0], Is.Empty); Assert.That(new int[] { 1, 2, 3 }, Is.Not.Empty); // Inherited syntax Expect(new bool[0], Empty); Expect(new int[] { 1, 2, 3 }, Not.Empty); } #endregion #region TypeConstraint Tests [Test] public void ExactTypeTests() { // Classic syntax workarounds Assert.AreEqual(typeof(string), "Hello".GetType()); Assert.AreEqual("System.String", "Hello".GetType().FullName); Assert.AreNotEqual(typeof(int), "Hello".GetType()); Assert.AreNotEqual("System.Int32", "Hello".GetType().FullName); // Helper syntax Assert.That("Hello", Is.TypeOf(typeof(string))); Assert.That("Hello", Is.Not.TypeOf(typeof(int))); // Inherited syntax Expect( "Hello", TypeOf(typeof(string))); Expect( "Hello", Not.TypeOf(typeof(int))); } [Test] public void InstanceOfTypeTests() { // Classic syntax Assert.IsInstanceOf(typeof(string), "Hello"); Assert.IsNotInstanceOf(typeof(string), 5); // Helper syntax Assert.That("Hello", Is.InstanceOf(typeof(string))); Assert.That(5, Is.Not.InstanceOf(typeof(string))); // Inherited syntax Expect("Hello", InstanceOf(typeof(string))); Expect(5, Not.InstanceOf(typeof(string))); } [Test] public void AssignableFromTypeTests() { // Classic syntax Assert.IsAssignableFrom(typeof(string), "Hello"); Assert.IsNotAssignableFrom(typeof(string), 5); // Helper syntax Assert.That( "Hello", Is.AssignableFrom(typeof(string))); Assert.That( 5, Is.Not.AssignableFrom(typeof(string))); // Inherited syntax Expect( "Hello", AssignableFrom(typeof(string))); Expect( 5, Not.AssignableFrom(typeof(string))); } #endregion #region StringConstraint Tests [Test] public void SubstringTests() { string phrase = "Hello World!"; string[] array = new string[] { "abc", "bad", "dba" }; // Classic Syntax StringAssert.Contains("World", phrase); // Helper syntax Assert.That(phrase, Text.Contains("World")); // Only available using new syntax Assert.That(phrase, Text.DoesNotContain("goodbye")); Assert.That(phrase, Text.Contains("WORLD").IgnoreCase); Assert.That(phrase, Text.DoesNotContain("BYE").IgnoreCase); Assert.That(array, Text.All.Contains( "b" ) ); // Inherited syntax Expect(phrase, Contains("World")); // Only available using new syntax Expect(phrase, Not.Contains("goodbye")); Expect(phrase, Contains("WORLD").IgnoreCase); Expect(phrase, Not.Contains("BYE").IgnoreCase); Expect(array, All.Contains("b")); } [Test] public void StartsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic syntax StringAssert.StartsWith("Hello", phrase); // Helper syntax Assert.That(phrase, Text.StartsWith("Hello")); // Only available using new syntax Assert.That(phrase, Text.DoesNotStartWith("Hi!")); Assert.That(phrase, Text.StartsWith("HeLLo").IgnoreCase); Assert.That(phrase, Text.DoesNotStartWith("HI").IgnoreCase); Assert.That(greetings, Text.All.StartsWith("h").IgnoreCase); // Inherited syntax Expect(phrase, StartsWith("Hello")); // Only available using new syntax Expect(phrase, Not.StartsWith("Hi!")); Expect(phrase, StartsWith("HeLLo").IgnoreCase); Expect(phrase, Not.StartsWith("HI").IgnoreCase); Expect(greetings, All.StartsWith("h").IgnoreCase); } [Test] public void EndsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic Syntax StringAssert.EndsWith("!", phrase); // Helper syntax Assert.That(phrase, Text.EndsWith("!")); // Only available using new syntax Assert.That(phrase, Text.DoesNotEndWith("?")); Assert.That(phrase, Text.EndsWith("WORLD!").IgnoreCase); Assert.That(greetings, Text.All.EndsWith("!")); // Inherited syntax Expect(phrase, EndsWith("!")); // Only available using new syntax Expect(phrase, Not.EndsWith("?")); Expect(phrase, EndsWith("WORLD!").IgnoreCase); Expect(greetings, All.EndsWith("!") ); } [Test] public void EqualIgnoringCaseTests() { string phrase = "Hello World!"; // Classic syntax StringAssert.AreEqualIgnoringCase("hello world!",phrase); // Helper syntax Assert.That(phrase, Is.EqualTo("hello world!").IgnoreCase); //Only available using new syntax Assert.That(phrase, Is.Not.EqualTo("goodbye world!").IgnoreCase); Assert.That(new string[] { "Hello", "World" }, Is.EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Assert.That(new string[] {"HELLO", "Hello", "hello" }, Is.All.EqualTo( "hello" ).IgnoreCase); // Inherited syntax Expect(phrase, EqualTo("hello world!").IgnoreCase); //Only available using new syntax Expect(phrase, Not.EqualTo("goodbye world!").IgnoreCase); Expect(new string[] { "Hello", "World" }, EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Expect(new string[] {"HELLO", "Hello", "hello" }, All.EqualTo( "hello" ).IgnoreCase); } [Test] public void RegularExpressionTests() { string phrase = "Now is the time for all good men to come to the aid of their country."; string[] quotes = new string[] { "Never say never", "It's never too late", "Nevermore!" }; // Classic syntax StringAssert.IsMatch( "all good men", phrase ); StringAssert.IsMatch( "Now.*come", phrase ); // Helper syntax Assert.That( phrase, Text.Matches( "all good men" ) ); Assert.That( phrase, Text.Matches( "Now.*come" ) ); // Only available using new syntax Assert.That(phrase, Text.DoesNotMatch("all.*men.*good")); Assert.That(phrase, Text.Matches("ALL").IgnoreCase); Assert.That(quotes, Text.All.Matches("never").IgnoreCase); // Inherited syntax Expect( phrase, Matches( "all good men" ) ); Expect( phrase, Matches( "Now.*come" ) ); // Only available using new syntax Expect(phrase, Not.Matches("all.*men.*good")); Expect(phrase, Matches("ALL").IgnoreCase); Expect(quotes, All.Matches("never").IgnoreCase); } #endregion #region Equality Tests [Test] public void EqualityTests() { int[] i3 = new int[] { 1, 2, 3 }; double[] d3 = new double[] { 1.0, 2.0, 3.0 }; int[] iunequal = new int[] { 1, 3, 2 }; // Classic Syntax Assert.AreEqual(4, 2 + 2); Assert.AreEqual(i3, d3); Assert.AreNotEqual(5, 2 + 2); Assert.AreNotEqual(i3, iunequal); // Helper syntax Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(2 + 2 == 4); Assert.That(i3, Is.EqualTo(d3)); Assert.That(2 + 2, Is.Not.EqualTo(5)); Assert.That(i3, Is.Not.EqualTo(iunequal)); // Inherited syntax Expect(2 + 2, EqualTo(4)); Expect(2 + 2 == 4); Expect(i3, EqualTo(d3)); Expect(2 + 2, Not.EqualTo(5)); Expect(i3, Not.EqualTo(iunequal)); } [Test] public void EqualityTestsWithTolerance() { // CLassic syntax Assert.AreEqual(5.0d, 4.99d, 0.05d); Assert.AreEqual(5.0f, 4.99f, 0.05f); // Helper syntax Assert.That(4.99d, Is.EqualTo(5.0d).Within(0.05d)); Assert.That(4.0d, Is.Not.EqualTo(5.0d).Within(0.5d)); Assert.That(4.99f, Is.EqualTo(5.0f).Within(0.05f)); Assert.That(4.99m, Is.EqualTo(5.0m).Within(0.05m)); Assert.That(3999999999u, Is.EqualTo(4000000000u).Within(5u)); Assert.That(499, Is.EqualTo(500).Within(5)); Assert.That(4999999999L, Is.EqualTo(5000000000L).Within(5L)); Assert.That(5999999999ul, Is.EqualTo(6000000000ul).Within(5ul)); // Inherited syntax Expect(4.99d, EqualTo(5.0d).Within(0.05d)); Expect(4.0d, Not.EqualTo(5.0d).Within(0.5d)); Expect(4.99f, EqualTo(5.0f).Within(0.05f)); Expect(4.99m, EqualTo(5.0m).Within(0.05m)); Expect(499u, EqualTo(500u).Within(5u)); Expect(499, EqualTo(500).Within(5)); Expect(4999999999L, EqualTo(5000000000L).Within(5L)); Expect(5999999999ul, EqualTo(6000000000ul).Within(5ul)); } [Test] public void EqualityTestsWithTolerance_MixedFloatAndDouble() { // Bug Fix 1743844 Assert.That(2.20492d, Is.EqualTo(2.2d).Within(0.01f), "Double actual, Double expected, Single tolerance"); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01d), "Double actual, Single expected, Double tolerance" ); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01f), "Double actual, Single expected, Single tolerance" ); Assert.That(2.20492f, Is.EqualTo(2.2f).Within(0.01d), "Single actual, Single expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01d), "Single actual, Double expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01f), "Single actual, Double expected, Single tolerance"); } [Test] public void EqualityTestsWithTolerance_MixingTypesGenerally() { // Extending tolerance to all numeric types Assert.That(202d, Is.EqualTo(200d).Within(2), "Double actual, Double expected, int tolerance"); Assert.That( 4.87m, Is.EqualTo(5).Within(.25), "Decimal actual, int expected, Double tolerance" ); Assert.That( 4.87m, Is.EqualTo(5ul).Within(1), "Decimal actual, ulong expected, int tolerance" ); Assert.That( 487, Is.EqualTo(500).Within(25), "int actual, int expected, int tolerance" ); Assert.That( 487u, Is.EqualTo(500).Within(25), "uint actual, int expected, int tolerance" ); Assert.That( 487L, Is.EqualTo(500).Within(25), "long actual, int expected, int tolerance" ); Assert.That( 487ul, Is.EqualTo(500).Within(25), "ulong actual, int expected, int tolerance" ); } #endregion #region Comparison Tests [Test] public void ComparisonTests() { // Classic Syntax Assert.Greater(7, 3); Assert.GreaterOrEqual(7, 3); Assert.GreaterOrEqual(7, 7); // Helper syntax Assert.That(7, Is.GreaterThan(3)); Assert.That(7, Is.GreaterThanOrEqualTo(3)); Assert.That(7, Is.AtLeast(3)); Assert.That(7, Is.GreaterThanOrEqualTo(7)); Assert.That(7, Is.AtLeast(7)); // Inherited syntax Expect(7, GreaterThan(3)); Expect(7, GreaterThanOrEqualTo(3)); Expect(7, AtLeast(3)); Expect(7, GreaterThanOrEqualTo(7)); Expect(7, AtLeast(7)); // Classic syntax Assert.Less(3, 7); Assert.LessOrEqual(3, 7); Assert.LessOrEqual(3, 3); // Helper syntax Assert.That(3, Is.LessThan(7)); Assert.That(3, Is.LessThanOrEqualTo(7)); Assert.That(3, Is.AtMost(7)); Assert.That(3, Is.LessThanOrEqualTo(3)); Assert.That(3, Is.AtMost(3)); // Inherited syntax Expect(3, LessThan(7)); Expect(3, LessThanOrEqualTo(7)); Expect(3, AtMost(7)); Expect(3, LessThanOrEqualTo(3)); Expect(3, AtMost(3)); } #endregion #region Collection Tests [Test] public void AllItemsTests() { object[] ints = new object[] { 1, 2, 3, 4 }; object[] doubles = new object[] { 0.99, 2.1, 3.0, 4.05 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Classic syntax CollectionAssert.AllItemsAreNotNull(ints); CollectionAssert.AllItemsAreInstancesOfType(ints, typeof(int)); CollectionAssert.AllItemsAreInstancesOfType(strings, typeof(string)); CollectionAssert.AllItemsAreUnique(ints); // Helper syntax Assert.That(ints, Is.All.Not.Null); Assert.That(ints, Has.None.Null); Assert.That(ints, Is.All.InstanceOfType(typeof(int))); Assert.That(ints, Has.All.InstanceOfType(typeof(int))); Assert.That(strings, Is.All.InstanceOfType(typeof(string))); Assert.That(strings, Has.All.InstanceOfType(typeof(string))); Assert.That(ints, Is.Unique); // Only available using new syntax Assert.That(strings, Is.Not.Unique); Assert.That(ints, Is.All.GreaterThan(0)); Assert.That(ints, Has.All.GreaterThan(0)); Assert.That(ints, Has.None.LessThanOrEqualTo(0)); Assert.That(strings, Text.All.Contains( "a" ) ); Assert.That(strings, Has.All.Contains( "a" ) ); Assert.That(strings, Has.Some.StartsWith( "ba" ) ); Assert.That( strings, Has.Some.Property( "Length" ).EqualTo( 3 ) ); Assert.That( strings, Has.Some.StartsWith( "BA" ).IgnoreCase ); Assert.That( doubles, Has.Some.EqualTo( 1.0 ).Within( .05 ) ); // Inherited syntax Expect(ints, All.Not.Null); Expect(ints, None.Null); Expect(ints, All.InstanceOfType(typeof(int))); Expect(strings, All.InstanceOfType(typeof(string))); Expect(ints, Unique); // Only available using new syntax Expect(strings, Not.Unique); Expect(ints, All.GreaterThan(0)); Expect(ints, None.LessThanOrEqualTo(0)); Expect(strings, All.Contains( "a" ) ); Expect(strings, Some.StartsWith( "ba" ) ); Expect(strings, Some.StartsWith( "BA" ).IgnoreCase ); Expect(doubles, Some.EqualTo( 1.0 ).Within( .05 ) ); } [Test] public void SomeItemTests() { object[] mixed = new object[] { 1, 2, "3", null, "four", 100 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Helper syntax Assert.That(mixed, Has.Some.Null); Assert.That(mixed, Has.Some.InstanceOfType(typeof(int))); Assert.That(mixed, Has.Some.InstanceOfType(typeof(string))); Assert.That(strings, Has.Some.StartsWith( "ba" ) ); Assert.That(strings, Has.Some.Not.StartsWith( "ba" ) ); // Inherited syntax Expect(mixed, Some.Null); Expect(mixed, Some.InstanceOfType(typeof(int))); Expect(mixed, Some.InstanceOfType(typeof(string))); Expect(strings, Some.StartsWith( "ba" ) ); Expect(strings, Some.Not.StartsWith( "ba" ) ); } [Test] public void NoItemTests() { object[] ints = new object[] { 1, 2, 3, 4, 5 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Helper syntax Assert.That(ints, Has.None.Null); Assert.That(ints, Has.None.InstanceOfType(typeof(string))); Assert.That(ints, Has.None.GreaterThan(99)); Assert.That(strings, Has.None.StartsWith( "qu" ) ); // Inherited syntax Expect(ints, None.Null); Expect(ints, None.InstanceOfType(typeof(string))); Expect(ints, None.GreaterThan(99)); Expect(strings, None.StartsWith( "qu" ) ); } [Test] public void CollectionContainsTests() { int[] iarray = new int[] { 1, 2, 3 }; string[] sarray = new string[] { "a", "b", "c" }; // Classic syntax Assert.Contains(3, iarray); Assert.Contains("b", sarray); CollectionAssert.Contains(iarray, 3); CollectionAssert.Contains(sarray, "b"); CollectionAssert.DoesNotContain(sarray, "x"); // Showing that Contains uses NUnit equality CollectionAssert.Contains( iarray, 1.0d ); // Helper syntax Assert.That(iarray, Has.Member(3)); Assert.That(sarray, Has.Member("b")); Assert.That(sarray, Has.No.Member("x")); // Showing that Contains uses NUnit equality Assert.That(iarray, Has.Member( 1.0d )); // Only available using the new syntax // Note that EqualTo and SameAs do NOT give // identical results to Contains because // Contains uses Object.Equals() Assert.That(iarray, Has.Some.EqualTo(3)); Assert.That(iarray, Has.Member(3)); Assert.That(sarray, Has.Some.EqualTo("b")); Assert.That(sarray, Has.None.EqualTo("x")); Assert.That(iarray, Has.None.SameAs( 1.0d )); Assert.That(iarray, Has.All.LessThan(10)); Assert.That(sarray, Has.All.Length.EqualTo(1)); Assert.That(sarray, Has.None.Property("Length").GreaterThan(3)); // Inherited syntax Expect(iarray, Contains(3)); Expect(sarray, Contains("b")); Expect(sarray, Not.Contains("x")); // Only available using new syntax // Note that EqualTo and SameAs do NOT give // identical results to Contains because // Contains uses Object.Equals() Expect(iarray, Some.EqualTo(3)); Expect(sarray, Some.EqualTo("b")); Expect(sarray, None.EqualTo("x")); Expect(iarray, All.LessThan(10)); Expect(sarray, All.Length.EqualTo(1)); Expect(sarray, None.Property("Length").GreaterThan(3)); } [Test] public void CollectionEquivalenceTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; int[] twothrees = new int[] { 1, 2, 3, 3, 4, 5 }; int[] twofours = new int[] { 1, 2, 3, 4, 4, 5 }; // Classic syntax CollectionAssert.AreEquivalent(new int[] { 2, 1, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 2, 1, 1, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(twothrees, twofours); // Helper syntax Assert.That(new int[] { 2, 1, 4, 3, 5 }, Is.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); // Inherited syntax Expect(new int[] { 2, 1, 4, 3, 5 }, EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); } [Test] public void SubsetTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; // Classic syntax CollectionAssert.IsSubsetOf(new int[] { 1, 3, 5 }, ints1to5); CollectionAssert.IsSubsetOf(new int[] { 1, 2, 3, 4, 5 }, ints1to5); CollectionAssert.IsNotSubsetOf(new int[] { 2, 4, 6 }, ints1to5); CollectionAssert.IsNotSubsetOf(new int[] { 1, 2, 2, 2, 5 }, ints1to5); // Helper syntax Assert.That(new int[] { 1, 3, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 1, 2, 3, 4, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 2, 4, 6 }, Is.Not.SubsetOf(ints1to5)); // Inherited syntax Expect(new int[] { 1, 3, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 1, 2, 3, 4, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 2, 4, 6 }, Not.SubsetOf(ints1to5)); } #endregion #region Property Tests [Test] public void PropertyTests() { string[] array = { "abc", "bca", "xyz", "qrs" }; string[] array2 = { "a", "ab", "abc" }; ArrayList list = new ArrayList( array ); // Not available using the classic syntax // Helper syntax Assert.That( list, Has.Property( "Count" ) ); Assert.That( list, Has.No.Property( "Length" ) ); Assert.That( "Hello", Has.Length.EqualTo( 5 ) ); Assert.That( "Hello", Has.Length.LessThan( 10 ) ); Assert.That( "Hello", Has.Property("Length").EqualTo(5) ); Assert.That( "Hello", Has.Property("Length").GreaterThan(3) ); Assert.That( array, Has.Property( "Length" ).EqualTo( 4 ) ); Assert.That( array, Has.Length.EqualTo( 4 ) ); Assert.That( array, Has.Property( "Length" ).LessThan( 10 ) ); Assert.That( array, Has.All.Property("Length").EqualTo(3) ); Assert.That( array, Has.All.Length.EqualTo( 3 ) ); Assert.That( array, Is.All.Length.EqualTo( 3 ) ); Assert.That( array, Has.All.Property("Length").EqualTo(3) ); Assert.That( array, Is.All.Property("Length").EqualTo(3) ); Assert.That( array2, Has.Some.Property("Length").EqualTo(2) ); Assert.That( array2, Has.Some.Length.EqualTo(2) ); Assert.That( array2, Has.Some.Property("Length").GreaterThan(2) ); Assert.That( array2, Is.Not.Property("Length").EqualTo(4) ); Assert.That( array2, Is.Not.Length.EqualTo( 4 ) ); Assert.That( array2, Has.No.Property("Length").GreaterThan(3) ); Assert.That( List.Map( array2 ).Property("Length"), Is.EqualTo( new int[] { 1, 2, 3 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.EquivalentTo( new int[] { 3, 2, 1 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.SubsetOf( new int[] { 1, 2, 3, 4, 5 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.Unique ); Assert.That( list, Has.Count.EqualTo( 4 ) ); // Inherited syntax Expect( list, Property( "Count" ) ); Expect( list, Not.Property( "Nada" ) ); Expect( "Hello", Length.EqualTo( 5 ) ); Expect( "Hello", Property("Length").EqualTo(5) ); Expect( "Hello", Property("Length").GreaterThan(0) ); Expect( array, Property("Length").EqualTo(4) ); Expect( array, Length.EqualTo(4) ); Expect( array, Property("Length").LessThan(10)); Expect( array, All.Length.EqualTo( 3 ) ); Expect( array, All.Property("Length").EqualTo(3)); Expect( array2, Some.Property("Length").EqualTo(2) ); Expect( array2, Some.Length.EqualTo( 2 ) ); Expect( array2, Some.Property("Length").GreaterThan(2)); Expect( array2, None.Property("Length").EqualTo(4) ); Expect( array2, None.Length.EqualTo( 4 ) ); Expect( array2, None.Property("Length").GreaterThan(3)); Expect( Map( array2 ).Property("Length"), EqualTo( new int[] { 1, 2, 3 } ) ); Expect( Map( array2 ).Property("Length"), EquivalentTo( new int[] { 3, 2, 1 } ) ); Expect( Map( array2 ).Property("Length"), SubsetOf( new int[] { 1, 2, 3, 4, 5 } ) ); Expect( Map( array2 ).Property("Length"), Unique ); Expect( list, Count.EqualTo( 4 ) ); } #endregion #region Not Tests [Test] public void NotTests() { // Not available using the classic syntax // Helper syntax Assert.That(42, Is.Not.Null); Assert.That(42, Is.Not.True); Assert.That(42, Is.Not.False); Assert.That(2.5, Is.Not.NaN); Assert.That(2 + 2, Is.Not.EqualTo(3)); Assert.That(2 + 2, Is.Not.Not.EqualTo(4)); Assert.That(2 + 2, Is.Not.Not.Not.EqualTo(5)); // Inherited syntax Expect(42, Not.Null); Expect(42, Not.True); Expect(42, Not.False); Expect(2.5, Not.NaN); Expect(2 + 2, Not.EqualTo(3)); Expect(2 + 2, Not.Not.EqualTo(4)); Expect(2 + 2, Not.Not.Not.EqualTo(5)); } #endregion #region Operator Tests [Test] public void NotOperator() { // The ! operator is only available in the new syntax Assert.That(42, !Is.Null); // Inherited syntax Expect( 42, !Null ); } [Test] public void AndOperator() { // The & operator is only available in the new syntax Assert.That(7, Is.GreaterThan(5) & Is.LessThan(10)); // Inherited syntax Expect( 7, GreaterThan(5) & LessThan(10)); } [Test] public void OrOperator() { // The | operator is only available in the new syntax Assert.That(3, Is.LessThan(5) | Is.GreaterThan(10)); Expect( 3, LessThan(5) | GreaterThan(10)); } [Test] public void ComplexTests() { Assert.That(7, Is.Not.Null & Is.Not.LessThan(5) & Is.Not.GreaterThan(10)); Expect(7, Not.Null & Not.LessThan(5) & Not.GreaterThan(10)); Assert.That(7, !Is.Null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !Null & !LessThan(5) & !GreaterThan(10)); // TODO: Remove #if when mono compiler can handle null #if MONO Constraint x = null; Assert.That(7, !x & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !x & !LessThan(5) & !GreaterThan(10)); #else Assert.That(7, !(Constraint)null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !(Constraint)null & !LessThan(5) & !GreaterThan(10)); #endif } #endregion #region Invalid Code Tests // This method contains assertions that should not compile // You can check by uncommenting it. //public void WillNotCompile() //{ // Assert.That(42, Is.Not); // Assert.That(42, Is.All); // Assert.That(42, Is.Null.Not); // Assert.That(42, Is.Not.Null.GreaterThan(10)); // Assert.That(42, Is.GreaterThan(10).LessThan(99)); // object[] c = new object[0]; // Assert.That(c, Is.Null.All); // Assert.That(c, Is.Not.All); // Assert.That(c, Is.All.Not); //} #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Whitelog.Barak.Common.DataStructures.Dictionary { /// <summary> /// Dictionary With TryGetValue Safe for multi thread. /// </summary> public class ReadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { public delegate TValue UpdateFactory(TKey key, TValue oldValue, TValue newValue); private class Entry { public Entry(TKey key,TValue value ) { Key = key; Value = value; } public TKey Key; public TValue Value; public Entry Next; } private class DictionaryBuffer { public readonly Entry[] array; public readonly int m_arrayModMask; public DictionaryBuffer(Entry[] keyValuePairs, int arrayModMask) { m_arrayModMask = arrayModMask; array = keyValuePairs; } } private static readonly IMaintenanceMode DefaultMaintenanceMode = new IncressSizeOnlyMaintenanceMode(4096, 0.2, 2); private readonly IEqualityComparer<TKey> m_comparer; private readonly HashSet<Entry> m_items = new HashSet<Entry>(); private readonly IMaintenanceMode m_maintenanceMode; private DictionaryBuffer m_dictionaryBuffer; private int m_maxDuplicateHashCount; public ReadSafeDictionary() : this(EqualityComparer<TKey>.Default, DefaultMaintenanceMode) { } public ReadSafeDictionary(IEqualityComparer<TKey> comparer) : this(comparer, DefaultMaintenanceMode) { } public ReadSafeDictionary(IMaintenanceMode maintenanceMode) : this(EqualityComparer<TKey>.Default, maintenanceMode) { } public ReadSafeDictionary(IEqualityComparer<TKey> comparer, IMaintenanceMode maintenanceMode) { m_maintenanceMode = maintenanceMode; m_comparer = comparer; Rebuild(m_maintenanceMode.ExpectedSize(0, 0, 0)); } private static int CeilingNextPowerOfTwo(int x) { var result = 2; while (result < x) { result *= 2; } return result; } /// <summary> /// This is the only safe method /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool TryGetValue(TKey key, out TValue value) { DictionaryBuffer dictionaryBuffer = m_dictionaryBuffer; int keySequence = m_comparer.GetHashCode(key); var node = dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask]; while(node != null) { if (m_comparer.Equals(key, node.Key)) { value = node.Value; return true; } node = node.Next; } value = default(TValue); return false; } public bool TryAdd(TKey key, TValue value) { DictionaryBuffer buffer = m_dictionaryBuffer; return TryAdd(new KeyValuePair<TKey, TValue>(key, value), buffer, true); } public void AddOrUpdate(TKey key, TValue value, UpdateFactory updateFactory) { DictionaryBuffer dictionaryBuffer = m_dictionaryBuffer; int keySequence = m_comparer.GetHashCode(key); Entry node = dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask]; int level = 1; if (node == null) { node = new Entry(key, value); dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask] = node; } else { Entry prevNode = null; // Check if the key already exsist // And move to the last item while (node != null) { level++; if (m_comparer.Equals(key, node.Key)) { // Replate the current node node.Value = updateFactory.Invoke(key, node.Value, value); return; // Exit the funciton we are done here } prevNode = node; node = node.Next; } level++; prevNode.Next = node = new Entry(key, value); } m_maxDuplicateHashCount = Math.Max(m_maxDuplicateHashCount, level); m_items.Add(node); int expectedSize = m_maintenanceMode.ExpectedSize(dictionaryBuffer.array.Length, m_items.Count, m_maxDuplicateHashCount); if (expectedSize != dictionaryBuffer.array.Length) { Rebuild(expectedSize); } } public bool TryRemove(TKey key) { DictionaryBuffer dictionaryBuffer = m_dictionaryBuffer; int keySequence = m_comparer.GetHashCode(key); Entry node = dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask]; Entry prevnode = null; while (node != null) { if (m_comparer.Equals(key, node.Key)) { m_items.Remove(node); int expectedSize = m_maintenanceMode.ExpectedSize(dictionaryBuffer.array.Length, m_items.Count, m_maxDuplicateHashCount); if (expectedSize != dictionaryBuffer.array.Length) { Rebuild(expectedSize); } else { if (prevnode == null) { dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask] = node.Next; } else { prevnode.Next = node.Next; } } return true; } prevnode = node; node = node.Next; } return false; } private bool TryAdd(KeyValuePair<TKey, TValue> newItem, DictionaryBuffer dictionaryBuffer, bool addItem) { int keySequence = m_comparer.GetHashCode(newItem.Key); Entry node = dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask]; int level = 1; if (node == null) { node = new Entry(newItem.Key, newItem.Value); dictionaryBuffer.array[keySequence & dictionaryBuffer.m_arrayModMask] = node; } else { Entry prevNode = null; // Check if the key already exsist // And move to the last item while (node != null) { level++; if (m_comparer.Equals(newItem.Key,node.Key)) { return false; } prevNode = node; node = node.Next; } level++; prevNode.Next = node =new Entry(newItem.Key, newItem.Value); } m_maxDuplicateHashCount = Math.Max(m_maxDuplicateHashCount, level); if (addItem) { m_items.Add(node); } int expectedSize = m_maintenanceMode.ExpectedSize(dictionaryBuffer.array.Length, m_items.Count, m_maxDuplicateHashCount); if (expectedSize != dictionaryBuffer.array.Length) { Rebuild(expectedSize); } return true; } private void Rebuild(int size) { int sizeAsPowerOfTwo = CeilingNextPowerOfTwo(size); int arrayModMask = sizeAsPowerOfTwo - 1; Entry[] array = new Entry[sizeAsPowerOfTwo]; m_maxDuplicateHashCount = 0; DictionaryBuffer dicBuffer = new DictionaryBuffer(array, arrayModMask); foreach (var currItem in m_items) { TryAdd(new KeyValuePair<TKey, TValue>(currItem.Key, currItem.Value), dicBuffer, false); } m_dictionaryBuffer = dicBuffer; } public void Clear() { DictionaryBuffer buff = m_dictionaryBuffer; for (int i = 0; i < m_dictionaryBuffer.array.Length; i++) { buff.array[i] = null; } m_maxDuplicateHashCount = 0; m_items.Clear(); } #region IDictionary public void Add(TKey key, TValue value) { if (!TryAdd(key, value)) { throw new ArgumentException("An element with the same key already exists in the Dictionary"); } } public bool ContainsKey(TKey key) { TValue value; return TryGetValue(key, out value); } public ICollection<TKey> Keys { get { return new List<TKey>(System.Linq.Enumerable.Select(m_items, x => x.Key)); } } public bool Remove(TKey key) { return TryRemove(key); } public ICollection<TValue> Values { get { return new List<TValue>(System.Linq.Enumerable.Select(m_items, x => x.Value)); } } public TValue this[TKey key] { get { TValue value; if (TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } set { AddOrUpdate(key, value, (key1, oldValue, newValue) => newValue ); } } public void Add(KeyValuePair<TKey, TValue> item) { TryAdd(item.Key, item.Value); } public bool Contains(KeyValuePair<TKey, TValue> item) { TValue value; return TryGetValue(item.Key, out value); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { int count = arrayIndex; foreach (var entry in m_items) { array[count] = new KeyValuePair<TKey, TValue>(entry.Key, entry.Value); count++; } } public int Count { get { return m_items.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { return TryRemove(item.Key); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_items.Select(p => new KeyValuePair<TKey, TValue>(p.Key,p.Value)).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return m_items.Select(p => new KeyValuePair<TKey, TValue>(p.Key, p.Value)).GetEnumerator(); } #endregion #region IDictionary } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1587 #region Header /// /// JsonData.cs /// Generic type to hold JSON data (objects, arrays, and so on). This is /// the default type returned by JsonMapper.ToObject(). /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; #if (WIN_RT || WINDOWS_PHONE) using Amazon.MissingTypes; #endif namespace ThirdParty.Json.LitJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public IEnumerable<string> PropertyNames { get { EnsureDictionary(); return inst_object.Keys; } } public JsonData this[string prop_name] { get { EnsureDictionary (); JsonData data = null; inst_object.TryGetValue(prop_name, out data); return data; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (int number) { type = JsonType.Int; inst_int = number; } public JsonData (long number) { type = JsonType.Long; inst_long = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int) obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long) obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int && data.type != JsonType.Long) { throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); } return data.type == JsonType.Int?data.inst_int:(int)data.inst_long; } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Long && data.type != JsonType.Int) { throw new InvalidCastException ( "Instance of JsonData doesn't hold a long"); } return data.type == JsonType.Long? data.inst_long:data.inst_int; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt () { if (type != JsonType.Int && type!=JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return type == JsonType.Int ? inst_int : (int) inst_long; } long IJsonWrapper.GetLong () { if (type != JsonType.Long && type!=JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return type == JsonType.Long?inst_long:inst_int; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write(null); return; } if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) { //check between int and long if ((x.type != JsonType.Int && x.type != JsonType.Long)||(this.type != JsonType.Int && this.type != JsonType.Long)) { return false; } } switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int:{ if(x.IsLong){ if(x.inst_long < Int32.MinValue || x.inst_long > Int32.MaxValue) return false; return this.inst_int.Equals((int)x.inst_long); } return this.inst_int.Equals (x.inst_int); } case JsonType.Long:{ if(x.IsInt){ if(this.inst_long < Int32.MinValue || this.inst_long > Int32.MaxValue) return false; return x.inst_int.Equals((int)this.inst_long); } return this.inst_long.Equals (x.inst_long); } case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_int = default (Int32); break; case JsonType.Long: inst_long = default (Int64); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Double: return inst_double.ToString (); case JsonType.Int: return inst_int.ToString (); case JsonType.Long: return inst_long.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal abstract partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class SignatureInfo { protected readonly SemanticDocument Document; protected readonly State State; private IList<ITypeParameterSymbol> _typeParameters; private IDictionary<ITypeSymbol, ITypeParameterSymbol> _typeArgumentToTypeParameterMap; public SignatureInfo( SemanticDocument document, State state) { this.Document = document; this.State = state; } public IList<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken) { return _typeParameters ?? (_typeParameters = DetermineTypeParametersWorker(cancellationToken)); } protected abstract IList<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken); public ITypeSymbol DetermineReturnType(CancellationToken cancellationToken) { return FixType(DetermineReturnTypeWorker(cancellationToken), cancellationToken); } protected abstract IList<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken); protected abstract ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken); protected abstract IList<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken); protected abstract IList<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken); protected abstract IList<bool> DetermineParameterOptionality(CancellationToken cancellationToken); protected abstract IList<string> DetermineParameterNames(CancellationToken cancellationToken); internal IPropertySymbol GenerateProperty( SyntaxGenerator factory, bool isAbstract, bool includeSetter, CancellationToken cancellationToken) { var accessibility = DetermineAccessibility(isAbstract); var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: null, accessibility: accessibility, statements: GenerateStatements(factory, isAbstract, cancellationToken)); var setMethod = includeSetter ? getMethod : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: null, accessibility: accessibility, modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract), type: DetermineReturnType(cancellationToken), explicitInterfaceSymbol: null, name: this.State.IdentifierToken.ValueText, parameters: DetermineParameters(cancellationToken), getMethod: getMethod, setMethod: setMethod); } public IMethodSymbol GenerateMethod( SyntaxGenerator factory, bool isAbstract, CancellationToken cancellationToken) { var parameters = DetermineParameters(cancellationToken); var returnType = DetermineReturnType(cancellationToken); var isUnsafe = (parameters .Any(p => p.Type.IsUnsafe()) || returnType.IsUnsafe()) && !State.IsContainedInUnsafeType; var method = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: null, accessibility: DetermineAccessibility(isAbstract), modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract, isUnsafe: isUnsafe), returnType: returnType, explicitInterfaceSymbol: null, name: this.State.IdentifierToken.ValueText, typeParameters: DetermineTypeParameters(cancellationToken), parameters: parameters, statements: GenerateStatements(factory, isAbstract, cancellationToken), handlesExpressions: null, returnTypeAttributes: null, methodKind: State.MethodKind); // Ensure no conflicts between type parameter names and parameter names. var languageServiceProvider = this.Document.Project.Solution.Workspace.Services.GetLanguageServices(this.State.TypeToGenerateIn.Language); var syntaxFacts = languageServiceProvider.GetService<ISyntaxFactsService>(); var equalityComparer = syntaxFacts.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var reservedParameterNames = this.DetermineParameterNames(cancellationToken).ToSet(equalityComparer); var newTypeParameterNames = NameGenerator.EnsureUniqueness( method.TypeParameters.Select(t => t.Name).ToList(), n => !reservedParameterNames.Contains(n)); return method.RenameTypeParameters(newTypeParameterNames); } private ITypeSymbol FixType( ITypeSymbol typeSymbol, CancellationToken cancellationToken) { // A type can't refer to a type parameter that isn't available in the type we're // eventually generating into. var availableMethodTypeParameters = this.DetermineTypeParameters(cancellationToken); var availableTypeParameters = this.State.TypeToGenerateIn.GetAllTypeParameters(); var compilation = this.Document.SemanticModel.Compilation; var allTypeParameters = availableMethodTypeParameters.Concat(availableTypeParameters); var typeArgumentToTypeParameterMap = this.GetTypeArgumentToTypeParameterMap(cancellationToken); return typeSymbol.RemoveAnonymousTypes(compilation) .ReplaceTypeParametersBasedOnTypeConstraints(compilation, allTypeParameters, this.Document.Document.Project.Solution, cancellationToken) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation) .SubstituteTypes(typeArgumentToTypeParameterMap, new TypeGenerator()); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> GetTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { return _typeArgumentToTypeParameterMap ?? (_typeArgumentToTypeParameterMap = CreateTypeArgumentToTypeParameterMap(cancellationToken)); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> CreateTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { var typeArguments = this.DetermineTypeArguments(cancellationToken); var typeParameters = this.DetermineTypeParameters(cancellationToken); var result = new Dictionary<ITypeSymbol, ITypeParameterSymbol>(); for(var i = 0; i < typeArguments.Count; i++) { if (typeArguments[i] != null) { result[typeArguments[i]] = typeParameters[i]; } } return result; } private IList<SyntaxNode> GenerateStatements( SyntaxGenerator factory, bool isAbstract, CancellationToken cancellationToken) { var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(factory, this.Document, "System.NotImplementedException", cancellationToken); return isAbstract || State.TypeToGenerateIn.TypeKind == TypeKind.Interface || throwStatement == null ? null : new[] { throwStatement }; } private IList<IParameterSymbol> DetermineParameters(CancellationToken cancellationToken) { var modifiers = DetermineParameterModifiers(cancellationToken); var types = DetermineParameterTypes(cancellationToken).Select(t => FixType(t, cancellationToken)).ToList(); var optionality = DetermineParameterOptionality(cancellationToken); var names = DetermineParameterNames(cancellationToken); var result = new List<IParameterSymbol>(); for (var i = 0; i < modifiers.Count; i++) { result.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: null, refKind: modifiers[i], isParams: false, isOptional: optionality[i], type: types[i], name: names[i])); } return result; } private Accessibility DetermineAccessibility(bool isAbstract) { var containingType = this.State.ContainingType; // If we're generating into an interface, then we don't use any modifiers. if (State.TypeToGenerateIn.TypeKind != TypeKind.Interface) { // Otherwise, figure out what accessibility modifier to use and optionally // mark it as static. if (containingType.IsContainedWithin(State.TypeToGenerateIn) && !isAbstract) { return Accessibility.Private; } else if (DerivesFrom(containingType) && State.IsStatic) { // NOTE(cyrusn): We only generate protected in the case of statics. Consider // the case where we're generating into one of our base types. i.e.: // // class B : A { void Foo() { A a; a.Foo(); } // // In this case we can *not* mark the method as protected. 'B' can only // access protected members of 'A' through an instance of 'B' (or a subclass // of B). It can not access protected members through an instance of the // superclass. In this case we need to make the method public or internal. // // However, this does not apply if the method will be static. i.e. // // class B : A { void Foo() { A.Foo(); } // // B can access the protected statics of A, and so we generate 'Foo' as // protected. // TODO: Code coverage return Accessibility.Protected; } else if (containingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(State.TypeToGenerateIn.ContainingAssembly)) { return Accessibility.Internal; } else { // TODO: Code coverage return Accessibility.Public; } } return Accessibility.NotApplicable; } private bool DerivesFrom(INamedTypeSymbol containingType) { return containingType.GetBaseTypes().Select(t => t.OriginalDefinition) .OfType<INamedTypeSymbol>() .Contains(State.TypeToGenerateIn); } } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\rectGrid.tcl // output file is AVrectGrid.cs /// <summary> /// The testing class derived from AVrectGrid /// </summary> public class AVrectGridClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVrectGrid(String [] argv) { //Prefix Content is: "" VTK_VARY_RADIUS_BY_VECTOR = 2; // create pipeline[] //[] reader = new vtkDataSetReader(); reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/RectGrid2.vtk"); reader.Update(); toRectilinearGrid = new vtkCastToConcrete(); toRectilinearGrid.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); plane = new vtkRectilinearGridGeometryFilter(); plane.SetInput((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput()); plane.SetExtent((int)0,(int)100,(int)0,(int)100,(int)15,(int)15); warper = new vtkWarpVector(); warper.SetInputConnection((vtkAlgorithmOutput)plane.GetOutputPort()); warper.SetScaleFactor((double)0.05); planeMapper = new vtkDataSetMapper(); planeMapper.SetInputConnection((vtkAlgorithmOutput)warper.GetOutputPort()); planeMapper.SetScalarRange((double)0.197813,(double)0.710419); planeActor = new vtkActor(); planeActor.SetMapper((vtkMapper)planeMapper); cutPlane = new vtkPlane(); cutPlane.SetOrigin(reader.GetOutput().GetCenter()[0],reader.GetOutput().GetCenter()[1],reader.GetOutput().GetCenter()[2]); cutPlane.SetNormal((double)1,(double)0,(double)0); planeCut = new vtkCutter(); planeCut.SetInput((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput()); planeCut.SetCutFunction((vtkImplicitFunction)cutPlane); cutMapper = new vtkDataSetMapper(); cutMapper.SetInputConnection((vtkAlgorithmOutput)planeCut.GetOutputPort()); cutMapper.SetScalarRange((double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[1]); cutActor = new vtkActor(); cutActor.SetMapper((vtkMapper)cutMapper); iso = new vtkContourFilter(); iso.SetInput((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput()); iso.SetValue((int)0,(double)0.7); normals = new vtkPolyDataNormals(); normals.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort()); normals.SetFeatureAngle((double)45); isoMapper = vtkPolyDataMapper.New(); isoMapper.SetInputConnection((vtkAlgorithmOutput)normals.GetOutputPort()); isoMapper.ScalarVisibilityOff(); isoActor = new vtkActor(); isoActor.SetMapper((vtkMapper)isoMapper); isoActor.GetProperty().SetColor((double) 1.0000, 0.8941, 0.7686 ); isoActor.GetProperty().SetRepresentationToWireframe(); streamer = new vtkStreamLine(); streamer.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); streamer.SetStartPosition((double)-1.2,(double)-0.1,(double)1.3); streamer.SetMaximumPropagationTime((double)500); streamer.SetStepLength((double)0.05); streamer.SetIntegrationStepLength((double)0.05); streamer.SetIntegrationDirectionToIntegrateBothDirections(); streamTube = new vtkTubeFilter(); streamTube.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort()); streamTube.SetRadius((double)0.025); streamTube.SetNumberOfSides((int)6); streamTube.SetVaryRadius((int)VTK_VARY_RADIUS_BY_VECTOR); mapStreamTube = vtkPolyDataMapper.New(); mapStreamTube.SetInputConnection((vtkAlgorithmOutput)streamTube.GetOutputPort()); mapStreamTube.SetScalarRange((double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[1]); streamTubeActor = new vtkActor(); streamTubeActor.SetMapper((vtkMapper)mapStreamTube); streamTubeActor.GetProperty().BackfaceCullingOn(); outline = new vtkOutlineFilter(); outline.SetInput((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)outlineMapper); outlineActor.GetProperty().SetColor((double) 0.0000, 0.0000, 0.0000 ); // Graphics stuff[] // Create the RenderWindow, Renderer and both Actors[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // Add the actors to the renderer, set the background and size[] //[] ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)planeActor); ren1.AddActor((vtkProp)cutActor); ren1.AddActor((vtkProp)isoActor); ren1.AddActor((vtkProp)streamTubeActor); ren1.SetBackground((double)1,(double)1,(double)1); renWin.SetSize((int)400,(int)400); cam1 = ren1.GetActiveCamera(); cam1.SetClippingRange((double)3.76213,(double)10.712); cam1.SetFocalPoint((double)-0.0842503,(double)-0.136905,(double)0.610234); cam1.SetPosition((double)2.53813,(double)2.2678,(double)-5.22172); cam1.SetViewUp((double)-0.241047,(double)0.930635,(double)0.275343); iren.Initialize(); // render the image[] //[] // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static int VTK_VARY_RADIUS_BY_VECTOR; static vtkDataSetReader reader; static vtkCastToConcrete toRectilinearGrid; static vtkRectilinearGridGeometryFilter plane; static vtkWarpVector warper; static vtkDataSetMapper planeMapper; static vtkActor planeActor; static vtkPlane cutPlane; static vtkCutter planeCut; static vtkDataSetMapper cutMapper; static vtkActor cutActor; static vtkContourFilter iso; static vtkPolyDataNormals normals; static vtkPolyDataMapper isoMapper; static vtkActor isoActor; static vtkStreamLine streamer; static vtkTubeFilter streamTube; static vtkPolyDataMapper mapStreamTube; static vtkActor streamTubeActor; static vtkOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkCamera cam1; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int GetVTK_VARY_RADIUS_BY_VECTOR() { return VTK_VARY_RADIUS_BY_VECTOR; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_VARY_RADIUS_BY_VECTOR(int toSet) { VTK_VARY_RADIUS_BY_VECTOR = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetReader Getreader() { return reader; } ///<summary> A Set Method for Static Variables </summary> public static void Setreader(vtkDataSetReader toSet) { reader = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCastToConcrete GettoRectilinearGrid() { return toRectilinearGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SettoRectilinearGrid(vtkCastToConcrete toSet) { toRectilinearGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRectilinearGridGeometryFilter Getplane() { return plane; } ///<summary> A Set Method for Static Variables </summary> public static void Setplane(vtkRectilinearGridGeometryFilter toSet) { plane = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkWarpVector Getwarper() { return warper; } ///<summary> A Set Method for Static Variables </summary> public static void Setwarper(vtkWarpVector toSet) { warper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetplaneMapper() { return planeMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneMapper(vtkDataSetMapper toSet) { planeMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetplaneActor() { return planeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneActor(vtkActor toSet) { planeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPlane GetcutPlane() { return cutPlane; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutPlane(vtkPlane toSet) { cutPlane = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCutter GetplaneCut() { return planeCut; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneCut(vtkCutter toSet) { planeCut = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetcutMapper() { return cutMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutMapper(vtkDataSetMapper toSet) { cutMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetcutActor() { return cutActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutActor(vtkActor toSet) { cutActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkContourFilter Getiso() { return iso; } ///<summary> A Set Method for Static Variables </summary> public static void Setiso(vtkContourFilter toSet) { iso = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataNormals Getnormals() { return normals; } ///<summary> A Set Method for Static Variables </summary> public static void Setnormals(vtkPolyDataNormals toSet) { normals = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetisoMapper() { return isoMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetisoMapper(vtkPolyDataMapper toSet) { isoMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetisoActor() { return isoActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetisoActor(vtkActor toSet) { isoActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStreamLine Getstreamer() { return streamer; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamer(vtkStreamLine toSet) { streamer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTubeFilter GetstreamTube() { return streamTube; } ///<summary> A Set Method for Static Variables </summary> public static void SetstreamTube(vtkTubeFilter toSet) { streamTube = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapStreamTube() { return mapStreamTube; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapStreamTube(vtkPolyDataMapper toSet) { mapStreamTube = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetstreamTubeActor() { return streamTubeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetstreamTubeActor(vtkActor toSet) { streamTubeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetoutlineMapper() { return outlineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineMapper(vtkPolyDataMapper toSet) { outlineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera Getcam1() { return cam1; } ///<summary> A Set Method for Static Variables </summary> public static void Setcam1(vtkCamera toSet) { cam1 = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(reader!= null){reader.Dispose();} if(toRectilinearGrid!= null){toRectilinearGrid.Dispose();} if(plane!= null){plane.Dispose();} if(warper!= null){warper.Dispose();} if(planeMapper!= null){planeMapper.Dispose();} if(planeActor!= null){planeActor.Dispose();} if(cutPlane!= null){cutPlane.Dispose();} if(planeCut!= null){planeCut.Dispose();} if(cutMapper!= null){cutMapper.Dispose();} if(cutActor!= null){cutActor.Dispose();} if(iso!= null){iso.Dispose();} if(normals!= null){normals.Dispose();} if(isoMapper!= null){isoMapper.Dispose();} if(isoActor!= null){isoActor.Dispose();} if(streamer!= null){streamer.Dispose();} if(streamTube!= null){streamTube.Dispose();} if(mapStreamTube!= null){mapStreamTube.Dispose();} if(streamTubeActor!= null){streamTubeActor.Dispose();} if(outline!= null){outline.Dispose();} if(outlineMapper!= null){outlineMapper.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(cam1!= null){cam1.Dispose();} } } //--- end of script --//
namespace V1EstimationTool { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.treeProjects = new System.Windows.Forms.TreeView(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.configureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuBuckets = new System.Windows.Forms.ToolStripMenuItem(); this.menuBucketConfig = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.panel1 = new System.Windows.Forms.Panel(); this.chkSingleLevel = new System.Windows.Forms.CheckBox(); this.btnRefreshProjects = new System.Windows.Forms.Button(); this.storyList = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.columnHeader5 = new System.Windows.Forms.ColumnHeader(); this.columnHeader6 = new System.Windows.Forms.ColumnHeader(); this.columnHeader7 = new System.Windows.Forms.ColumnHeader(); this.iconList = new System.Windows.Forms.ImageList(this.components); this.btnRefreshStories = new System.Windows.Forms.Button(); this.panel2 = new System.Windows.Forms.Panel(); this.bucketPanel = new System.Windows.Forms.Panel(); this.btnSaveAll = new System.Windows.Forms.Button(); this.btnClearSort = new System.Windows.Forms.Button(); this.menuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // treeProjects // this.treeProjects.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.treeProjects.HideSelection = false; this.treeProjects.Location = new System.Drawing.Point(12, 47); this.treeProjects.Name = "treeProjects"; this.treeProjects.Size = new System.Drawing.Size(188, 489); this.treeProjects.TabIndex = 0; this.treeProjects.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeProjects_AfterSelect); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.menuBuckets}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.menuStrip1.Size = new System.Drawing.Size(792, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.configureToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // configureToolStripMenuItem // this.configureToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("configureToolStripMenuItem.Image"))); this.configureToolStripMenuItem.Name = "configureToolStripMenuItem"; this.configureToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.configureToolStripMenuItem.Text = "&Configure"; this.configureToolStripMenuItem.Click += new System.EventHandler(this.configureToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(129, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // menuBuckets // this.menuBuckets.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuBucketConfig, this.toolStripSeparator2}); this.menuBuckets.Name = "menuBuckets"; this.menuBuckets.Size = new System.Drawing.Size(56, 20); this.menuBuckets.Text = "&Buckets"; // // menuBucketConfig // this.menuBucketConfig.Image = ((System.Drawing.Image)(resources.GetObject("menuBucketConfig.Image"))); this.menuBucketConfig.Name = "menuBucketConfig"; this.menuBucketConfig.Size = new System.Drawing.Size(132, 22); this.menuBucketConfig.Text = "Configure"; this.menuBucketConfig.Click += new System.EventHandler(this.menuBucketConfig_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(129, 6); // // panel1 // this.panel1.Controls.Add(this.chkSingleLevel); this.panel1.Controls.Add(this.btnRefreshProjects); this.panel1.Controls.Add(this.treeProjects); this.panel1.Dock = System.Windows.Forms.DockStyle.Left; this.panel1.Location = new System.Drawing.Point(0, 24); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(212, 548); this.panel1.TabIndex = 3; // // chkSingleLevel // this.chkSingleLevel.AutoSize = true; this.chkSingleLevel.Location = new System.Drawing.Point(12, 18); this.chkSingleLevel.Name = "chkSingleLevel"; this.chkSingleLevel.Size = new System.Drawing.Size(146, 17); this.chkSingleLevel.TabIndex = 4; this.chkSingleLevel.Text = "Single-Level Project View"; this.chkSingleLevel.UseVisualStyleBackColor = true; this.chkSingleLevel.CheckedChanged += new System.EventHandler(this.chkSingleLevel_CheckedChanged); // // btnRefreshProjects // this.btnRefreshProjects.Image = ((System.Drawing.Image)(resources.GetObject("btnRefreshProjects.Image"))); this.btnRefreshProjects.Location = new System.Drawing.Point(168, 9); this.btnRefreshProjects.Name = "btnRefreshProjects"; this.btnRefreshProjects.Size = new System.Drawing.Size(32, 32); this.btnRefreshProjects.TabIndex = 4; this.btnRefreshProjects.UseVisualStyleBackColor = true; this.btnRefreshProjects.Click += new System.EventHandler(this.btnRefreshProjects_Click); // // storyList // this.storyList.AllowDrop = true; this.storyList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.storyList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4, this.columnHeader5, this.columnHeader6, this.columnHeader7}); this.storyList.Location = new System.Drawing.Point(3, 41); this.storyList.Name = "storyList"; this.storyList.Size = new System.Drawing.Size(559, 219); this.storyList.SmallImageList = this.iconList; this.storyList.TabIndex = 4; this.storyList.UseCompatibleStateImageBehavior = false; this.storyList.View = System.Windows.Forms.View.Details; this.storyList.DoubleClick += new System.EventHandler(this.storyList_DoubleClick); // // columnHeader1 // this.columnHeader1.Text = "Name"; // // columnHeader2 // this.columnHeader2.Text = "ID"; // // columnHeader3 // this.columnHeader3.Text = "Project"; // // columnHeader4 // this.columnHeader4.Text = "Iteration"; // // columnHeader5 // this.columnHeader5.Text = "Team"; // // columnHeader6 // this.columnHeader6.Text = "Theme"; // // columnHeader7 // this.columnHeader7.Text = "Estimate"; // // iconList // this.iconList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iconList.ImageStream"))); this.iconList.TransparentColor = System.Drawing.Color.Transparent; this.iconList.Images.SetKeyName(0, "Theme"); this.iconList.Images.SetKeyName(1, "Changeset"); this.iconList.Images.SetKeyName(2, "Defect"); this.iconList.Images.SetKeyName(3, "DefectTemplate"); this.iconList.Images.SetKeyName(4, "Epic"); this.iconList.Images.SetKeyName(5, "Goal"); this.iconList.Images.SetKeyName(6, "Issue"); this.iconList.Images.SetKeyName(7, "Iteration"); this.iconList.Images.SetKeyName(8, "Member"); this.iconList.Images.SetKeyName(9, "Note"); this.iconList.Images.SetKeyName(10, "Project"); this.iconList.Images.SetKeyName(11, "Request"); this.iconList.Images.SetKeyName(12, "Retrospective"); this.iconList.Images.SetKeyName(13, "Story"); this.iconList.Images.SetKeyName(14, "StoryTemplate"); this.iconList.Images.SetKeyName(15, "Task"); this.iconList.Images.SetKeyName(16, "Team"); this.iconList.Images.SetKeyName(17, "Test"); // // btnRefreshStories // this.btnRefreshStories.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnRefreshStories.Image = ((System.Drawing.Image)(resources.GetObject("btnRefreshStories.Image"))); this.btnRefreshStories.Location = new System.Drawing.Point(530, 3); this.btnRefreshStories.Name = "btnRefreshStories"; this.btnRefreshStories.Size = new System.Drawing.Size(32, 32); this.btnRefreshStories.TabIndex = 5; this.btnRefreshStories.UseVisualStyleBackColor = true; this.btnRefreshStories.Click += new System.EventHandler(this.btnRefreshStories_Click); // // panel2 // this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel2.Controls.Add(this.btnClearSort); this.panel2.Controls.Add(this.storyList); this.panel2.Controls.Add(this.btnRefreshStories); this.panel2.Location = new System.Drawing.Point(218, 300); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(574, 272); this.panel2.TabIndex = 11; // // bucketPanel // this.bucketPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bucketPanel.AutoScroll = true; this.bucketPanel.Location = new System.Drawing.Point(218, 71); this.bucketPanel.Name = "bucketPanel"; this.bucketPanel.Size = new System.Drawing.Size(574, 226); this.bucketPanel.TabIndex = 12; // // btnSaveAll // this.btnSaveAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSaveAll.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAll.Image"))); this.btnSaveAll.Location = new System.Drawing.Point(748, 33); this.btnSaveAll.Name = "btnSaveAll"; this.btnSaveAll.Size = new System.Drawing.Size(32, 32); this.btnSaveAll.TabIndex = 6; this.btnSaveAll.UseVisualStyleBackColor = true; this.btnSaveAll.Click += new System.EventHandler(this.btnSaveStoryList_Click); // // btnClearSort // this.btnClearSort.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClearSort.Image = ((System.Drawing.Image)(resources.GetObject("btnClearSort.Image"))); this.btnClearSort.Location = new System.Drawing.Point(492, 3); this.btnClearSort.Name = "btnClearSort"; this.btnClearSort.Size = new System.Drawing.Size(32, 32); this.btnClearSort.TabIndex = 6; this.btnClearSort.UseVisualStyleBackColor = true; this.btnClearSort.Click += new System.EventHandler(this.btnClearSort_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(792, 572); this.Controls.Add(this.btnSaveAll); this.Controls.Add(this.bucketPanel); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.Text = "VersionOne"; this.Load += new System.EventHandler(this.MainForm_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TreeView treeProjects; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem configureToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.Button btnRefreshProjects; private System.Windows.Forms.CheckBox chkSingleLevel; private System.Windows.Forms.ListView storyList; private System.Windows.Forms.Button btnRefreshStories; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Panel bucketPanel; private System.Windows.Forms.ImageList iconList; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.ColumnHeader columnHeader7; private System.Windows.Forms.ToolStripMenuItem menuBuckets; private System.Windows.Forms.Button btnSaveAll; private System.Windows.Forms.ToolStripMenuItem menuBucketConfig; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.Button btnClearSort; } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdProjProcure : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String Id; private int BOLocsId; private int b=0; protected void Page_Load(object sender, System.EventArgs e) { if (Session["btnAction"].ToString() == "Update") { Id=Session["ProjProcureId"].ToString(); } if (!IsPostBack) { lblOrg.Text=(Session["OrgName"]).ToString(); getQtyMeasure(); btnAction.Text= Session["btnAction"].ToString(); if (Session["btnAction"].ToString() == "Update") { loadData(); //loadGrid(); } else { //BOLocsId=0; //loadGrid(); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.Connection=this.epsDbConn; cmd.CommandText="fms_RetrieveProjProcure"; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Session["ProjProcureId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"Procure"); txtDesc.Text=ds.Tables["Procure"].Rows[0][0].ToString(); txtQty.Text=ds.Tables["Procure"].Rows[0][1].ToString(); BOLocsId=Int32.Parse(ds.Tables["Procure"].Rows[0][2].ToString()); } /*private void loadGrid() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveBOLocDetails"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@LocId",SqlDbType.Int); cmd.Parameters["@LocId"].Value=Session["LocId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"BudOrgs"); if (ds.Tables["BudOrgs"].Rows.Count == 0) { lblContent1.Text="Warning. There is no budget available for this location."; DataGrid1.Visible=false; } else { Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); refreshGrid(); } } private void refreshGrid() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[7].FindControl("cbxSel")); if (i.Cells[8].Text == "1") { i.Cells[6].Text="Open"; } else { i.Cells[6].Text="Close"; } if (i.Cells[0].Text==BOLocsId.ToString()) { cb.Checked=true; } } } private void checkGrid() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[7].FindControl("cbxSel")); if (cb.Checked) { a=++a; b=Int32.Parse(i.Cells[0].Text); } } if (a>1) { lblContent1.Text="Please Select only One budget to be charged."; } else updateGrid(); }*/ protected void btnAction_Click(object sender, System.EventArgs e) { //a=0; //b=0; //checkGrid(); updateGrid(); } private void updateGrid() { if (btnAction.Text == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_UpdateProjProcure"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Session["ProjProcureId"].ToString(); cmd.Parameters.Add ("@Desc",SqlDbType.NVarChar); cmd.Parameters["@Desc"].Value= txtDesc.Text; cmd.Parameters.Add ("@BOLocsId",SqlDbType.Int); cmd.Parameters["@BOLocsId"].Value=b; if (txtQty.Text != "") { cmd.Parameters.Add ("@Qty",SqlDbType.Decimal); cmd.Parameters["@Qty"].Value=Decimal.Parse(txtQty.Text, System.Globalization.NumberStyles.AllowDecimalPoint|System.Globalization.NumberStyles.AllowThousands); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else if (btnAction.Text == "Add") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_AddProjProcure"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Desc",SqlDbType.NVarChar); cmd.Parameters["@Desc"].Value= txtDesc.Text; cmd.Parameters.Add ("@PSEPSerId",SqlDbType.Int); cmd.Parameters["@PSEPSerId"].Value=Session["PSEPSerId"].ToString(); cmd.Parameters.Add ("@BOLocsId",SqlDbType.Int); cmd.Parameters["@BOLocsId"].Value=b; cmd.Parameters.Add("@OrgLocId",SqlDbType.Int); cmd.Parameters["@OrgLocId"].Value=Session["OrgLocId"].ToString(); cmd.Parameters.Add ("@ProjectId",SqlDbType.Int); cmd.Parameters["@ProjectId"].Value=Session["ProjectId"].ToString(); if (txtQty.Text != "") { cmd.Parameters.Add ("@Qty",SqlDbType.Decimal); cmd.Parameters["@Qty"].Value=Decimal.Parse(txtQty.Text, System.Globalization.NumberStyles.AllowDecimalPoint|System.Globalization.NumberStyles.AllowThousands); } cmd.Parameters.Add("@SGFlag",SqlDbType.Int); cmd.Parameters["@SGFlag"].Value=Session["SGFlag"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } } private void getQtyMeasure() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveQtyMName"; cmd.Parameters.Add("@Id",SqlDbType.Int); if (Session["SGFlag"].ToString() == "0") { cmd.Parameters["@Id"].Value=Session["ServiceTypesId"].ToString(); } else { cmd.Parameters["@Id"].Value=Session["ResTypesId"].ToString(); } cmd.Parameters.Add("@SGFlag",SqlDbType.Int); cmd.Parameters["@SGFlag"].Value=Session["SGFlag"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"QtyMeasure"); lblQtyMeasure.Text=ds.Tables["QtyMeasure"].Rows[0][0].ToString(); } private void Done() { Response.Redirect (strURL + Session["CUpdProjProcure"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } } }
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using System.Collections.Generic; using Unity.IL2CPP.CompilerServices; namespace Pixeye.Actors { [Il2CppSetOption(Option.NullChecks, false)] [Il2CppSetOption(Option.ArrayBoundsChecks, false)] [Il2CppSetOption(Option.DivideByZeroChecks, false)] public class ProcessorUpdate { internal readonly List<IReceiveEcsEvent> processors = new List<IReceiveEcsEvent>(64); internal readonly List<ITick> ticks = new List<ITick>(128); internal readonly List<ITick> ticksProc = new List<ITick>(64); internal readonly List<ITickFixed> ticksFixedProc = new List<ITickFixed>(64); internal readonly List<ITickLate> ticksLateProc = new List<ITickLate>(64); internal readonly List<ITickFixed> ticksFixed = new List<ITickFixed>(); internal readonly List<ITickLate> ticksLate = new List<ITickLate>(); // counting manually allows to instantly shut down everything when scene releasing without waiting one frame. int countTicksProc; int countTicksProcFixed; int countTicksProcLate; int countTicks; int countTicksFixed; int countTicksLate; internal Layer layer; internal int GetTicksCount => countTicks + countTicksFixed + countTicksLate + countTicksProc + countTicksProcFixed + countTicksProcLate; public void AddTick(object updateble) { ticks.Add(updateble as ITick); countTicks++; } public void RemoveTick(object updateble) { if (ticks.Remove(updateble as ITick)) { countTicks--; } } public void AddTickFixed(object updateble) { ticksFixed.Add(updateble as ITickFixed); countTicksFixed++; } public void RemoveTickFixed(object updateble) { if (ticksFixed.Remove(updateble as ITickFixed)) { countTicksFixed--; } } public void AddTickLate(object updateble) { ticksLate.Add(updateble as ITickLate); countTicksLate++; } public void RemoveTickLate(object updateble) { if (ticksLate.Remove(updateble as ITickLate)) { countTicksLate--; } } internal void AddProc(Processor updateble) { if (updateble is IReceiveEcsEvent receiver) { processors.Add(receiver); } if (updateble is ITick tickable) { ticksProc.Add(tickable); countTicksProc += 1; } else { ticksProc.Add(new Dummy()); countTicksProc += 1; } if (updateble is ITickFixed tickableFixed) { ticksFixedProc.Add(tickableFixed); countTicksProcFixed++; } if (updateble is ITickLate tickableLate) { ticksLateProc.Add(tickableLate); countTicksProcLate++; } } internal void RemoveProc(object updateble) { processors.Remove(updateble as IReceiveEcsEvent); if (ticksProc.Remove(updateble as ITick)) { countTicksProc--; } if (ticksFixedProc.Remove(updateble as ITickFixed)) { countTicksProcFixed--; } if (ticksLateProc.Remove(updateble as ITickLate)) { countTicksProcLate--; } } public void Add(object updateble) { if (updateble is ITick tickable) { ticks.Add(tickable); countTicks++; } if (updateble is ITickFixed tickableFixed) { ticksFixed.Add(tickableFixed); countTicksFixed++; } if (updateble is ITickLate tickableLate) { ticksLate.Add(tickableLate); countTicksLate++; } } public void Remove(object updateble) { if (ticks.Remove(updateble as ITick)) { countTicks--; } if (ticksFixed.Remove(updateble as ITickFixed)) { countTicksFixed--; } if (ticksLate.Remove(updateble as ITickLate)) { countTicksLate--; } } public void Update() { if (LayerKernel.ApplicationIsQuitting) return; if (layer.isReleasing) return; layer.Time.Tick(); var delta = layer.Time.deltaTime; for (var i = 0; i < countTicks; i++) { ticks[i].Tick(delta); } layer.processorEcs.Execute(); // dirty. we are using Dummy class for making all processors work here. // this is need for receiving ecs events. for (var i = 0; i < countTicksProc; i++) { processors[i].Receive(); ticksProc[i].Tick(delta); layer.processorEcs.Execute(); } } public void FixedUpdate() { if (LayerKernel.ApplicationIsQuitting) return; if (layer.isReleasing) return; var delta = layer.Time.deltaTimeFixed; for (var i = 0; i < countTicksFixed; i++) { ticksFixed[i].TickFixed(delta); } for (var i = 0; i < countTicksProcFixed; i++) { ticksFixedProc[i].TickFixed(delta); } } public void LateUpdate() { if (LayerKernel.ApplicationIsQuitting) return; if (layer.isReleasing) return; var delta = layer.Time.deltaTime; for (var i = 0; i < countTicksLate; i++) { ticksLate[i].TickLate(delta); } for (var i = 0; i < countTicksProcLate; i++) { ticksLateProc[i].TickLate(delta); } } internal void Dispose() { countTicks = 0; countTicksLate = 0; countTicksFixed = 0; countTicksProc = 0; countTicksProcFixed = 0; countTicksProcLate = 0; ticks.Clear(); ticksFixed.Clear(); ticksLate.Clear(); ticksProc.Clear(); ticksFixedProc.Clear(); ticksLateProc.Clear(); } } }