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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; internal static class IOInputs { // see: http://msdn.microsoft.com/en-us/library/aa365247.aspx private static readonly char[] s_invalidFileNameChars = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new char[] { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, '*', '?' } : new char[] { '\0' }; public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } } // Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system. public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000; // Same as MaxPath on Unix public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath; // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. public static readonly int MaxDirectory = 247; // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0. public static readonly int MaxExtendedPath = short.MaxValue - 1; public const int MaxComponent = 255; public const string ExtendedPrefix = @"\\?\"; public const string ExtendedUncPrefix = @"\\?\UNC\"; public static IEnumerable<string> GetValidPathComponentNames() { yield return Path.GetRandomFileName(); yield return "!@#$%^&"; yield return "\x65e5\x672c\x8a9e"; yield return "A"; yield return " A"; yield return " A"; yield return "FileName"; yield return "FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return "This is a valid component name"; yield return "This is a valid component name.txt"; yield return "V1.0.0.0000"; } public static IEnumerable<string> GetControlWhiteSpace() { yield return "\t"; yield return "\t\t"; yield return "\t\t\t"; yield return "\n"; yield return "\n\n"; yield return "\n\n\n"; yield return "\t\n"; yield return "\t\n\t\n"; yield return "\n\t\n"; yield return "\n\t\n\t"; } public static IEnumerable<string> GetSimpleWhiteSpace() { yield return " "; yield return " "; yield return " "; yield return " "; yield return " "; } public static IEnumerable<string> GetWhiteSpace() { return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace()); } public static IEnumerable<string> GetUncPathsWithoutShareName() { foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }) { string slashes = new string(slash, 2); yield return slashes; yield return slashes + " "; yield return slashes + new string(slash, 5); yield return slashes + "S"; yield return slashes + "S "; yield return slashes + "LOCALHOST"; yield return slashes + "LOCALHOST " + slash; yield return slashes + "LOCALHOST " + new string(slash, 2); yield return slashes + "LOCALHOST" + slash + " "; yield return slashes + "LOCALHOST" + slash + slash + " "; } } public static IEnumerable<string> GetPathsWithReservedDeviceNames() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); foreach (string deviceName in GetReservedDeviceNames()) { yield return deviceName; yield return Path.Combine(root, deviceName); yield return Path.Combine(root, "Directory", deviceName); yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName); } } public static IEnumerable<string> GetPathsWithAlternativeDataStreams() { yield return @"AA:"; yield return @"AAA:"; yield return @"AA:A"; yield return @"AAA:A"; yield return @"AA:AA"; yield return @"AAA:AA"; yield return @"AA:AAA"; yield return @"AAA:AAA"; yield return @"AA:FileName"; yield return @"AAA:FileName"; yield return @"AA:FileName.txt"; yield return @"AAA:FileName.txt"; yield return @"A:FileName.txt:"; yield return @"AA:FileName.txt:AA"; yield return @"AAA:FileName.txt:AAA"; yield return @"C:\:"; yield return @"C:\:FileName"; yield return @"C:\:FileName.txt"; yield return @"C:\fileName:"; yield return @"C:\fileName:FileName.txt"; yield return @"C:\fileName:FileName.txt:"; yield return @"C:\fileName:FileName.txt:AA"; yield return @"C:\fileName:FileName.txt:AAA"; yield return @"ftp://fileName:FileName.txt:AAA"; } public static IEnumerable<string> GetPathsWithInvalidColons() { // Windows specific. We document that these return NotSupportedException. yield return @":"; yield return @" :"; yield return @" :"; yield return @"C::"; yield return @"C::FileName"; yield return @"C::FileName.txt"; yield return @"C::FileName.txt:"; yield return @"C::FileName.txt::"; yield return @":f"; yield return @":filename"; yield return @"file:"; yield return @"file:file"; yield return @"http:"; yield return @"http:/"; yield return @"http://"; yield return @"http://www"; yield return @"http://www.microsoft.com"; yield return @"http://www.microsoft.com/index.html"; yield return @"http://server"; yield return @"http://server/"; yield return @"http://server/home"; yield return @"file://"; yield return @"file:///C|/My Documents/ALetter.html"; } public static IEnumerable<string> GetPathsWithInvalidCharacters() { // NOTE: That I/O treats "file"/http" specially and throws ArgumentException. // Otherwise, it treats all other urls as alternative data streams if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // alternate data streams, drive labels, etc. { yield return "\0"; yield return "middle\0path"; yield return "trailing\0"; yield return @"\\?\"; yield return @"\\?\UNC\"; yield return @"\\?\UNC\LOCALHOST"; } else { yield return "\0"; yield return "middle\0path"; yield return "trailing\0"; } foreach (char c in s_invalidFileNameChars) { yield return c.ToString(); } } public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent() { // While paths themselves can be up to and including 32,000 characters, most volumes // limit each component of the path to a total of 255 characters. string component = new string('s', MaxComponent + 1); yield return String.Format(@"C:\{0}", component); yield return String.Format(@"C:\{0}\Filename.txt", component); yield return String.Format(@"C:\{0}\Filename.txt\", component); yield return String.Format(@"\\{0}\Share", component); yield return String.Format(@"\\LOCALHOST\{0}", component); yield return String.Format(@"\\LOCALHOST\{0}\FileName.txt", component); yield return String.Format(@"\\LOCALHOST\Share\{0}", component); } public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath) { yield return GetLongPath(rootPath, MaxDirectory + 1); yield return GetLongPath(rootPath, MaxDirectory + 2); yield return GetLongPath(rootPath, MaxDirectory + 3); } public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax); } public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxExtendedPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxExtendedPath + 2, useExtendedSyntax); } private static string GetLongPath(string rootPath, int characterCount, bool extended = false) { return IOServices.GetPath(rootPath, characterCount, extended).FullPath; } public static IEnumerable<string> GetReservedDeviceNames() { // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx yield return "CON"; yield return "AUX"; yield return "NUL"; yield return "PRN"; yield return "COM1"; yield return "COM2"; yield return "COM3"; yield return "COM4"; yield return "COM5"; yield return "COM6"; yield return "COM7"; yield return "COM8"; yield return "COM9"; yield return "LPT1"; yield return "LPT2"; yield return "LPT3"; yield return "LPT4"; yield return "LPT5"; yield return "LPT6"; yield return "LPT7"; yield return "LPT8"; yield return "LPT9"; } }
// 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.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal sealed class InterpretedFrame { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] [ThreadStatic] private static InterpretedFrame s_currentFrame; internal readonly Interpreter Interpreter; internal InterpretedFrame _parent; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] private readonly int[] _continuations; private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly object[] Data; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly IStrongBox[] Closure; public int StackIndex; public int InstructionIndex; #if FEATURE_THREAD_ABORT // When a ThreadAbortException is raised from interpreted code this is the first frame that caught it. // No handlers within this handler re-abort the current thread when left. public ExceptionHandler CurrentAbortHandler; #endif internal InterpretedFrame(Interpreter interpreter, IStrongBox[] closure) { Interpreter = interpreter; StackIndex = interpreter.LocalCount; Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth]; int c = interpreter.Instructions.MaxContinuationDepth; if (c > 0) { _continuations = new int[c]; } Closure = closure; _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } public DebugInfo GetDebugInfo(int instructionIndex) { return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex); } public string Name => Interpreter.Name; #region Data Stack Operations public void Push(object value) { Data[StackIndex++] = value; } public void Push(bool value) { Data[StackIndex++] = value ? Utils.BoxedTrue : Utils.BoxedFalse; } public void Push(int value) { Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value); } public void Push(byte value) { Data[StackIndex++] = value; } public void Push(sbyte value) { Data[StackIndex++] = value; } public void Push(short value) { Data[StackIndex++] = value; } public void Push(ushort value) { Data[StackIndex++] = value; } public object Pop() { return Data[--StackIndex]; } internal void SetStackDepth(int depth) { StackIndex = Interpreter.LocalCount + depth; } public object Peek() { return Data[StackIndex - 1]; } public void Dup() { int i = StackIndex; Data[i] = Data[i - 1]; StackIndex = i + 1; } #endregion #region Stack Trace public InterpretedFrame Parent => _parent; public static bool IsInterpretedFrame(MethodBase method) { //ContractUtils.RequiresNotNull(method, nameof(method)); return method.DeclaringType == typeof(Interpreter) && method.Name == "Run"; } public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo() { InterpretedFrame frame = this; do { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; } while (frame != null); } internal void SaveTraceToException(Exception exception) { if (exception.Data[typeof(InterpretedFrameInfo)] == null) { exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray(); } } public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) { return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[]; } #if DEBUG internal string[] Trace { get { var trace = new List<string>(); InterpretedFrame frame = this; do { trace.Add(frame.Name); frame = frame.Parent; } while (frame != null); return trace.ToArray(); } } #endif internal InterpretedFrame Enter() { InterpretedFrame currentFrame = s_currentFrame; s_currentFrame = this; return _parent = currentFrame; } internal void Leave(InterpretedFrame prevFrame) { s_currentFrame = prevFrame; } #endregion #region Continuations internal bool IsJumpHappened() { return _pendingContinuation >= 0; } public void RemoveContinuation() { _continuationIndex--; } public void PushContinuation(int continuation) { _continuations[_continuationIndex++] = continuation; } public int YieldToCurrentContinuation() { RuntimeLabel target = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(target.StackDepth); return target.Index - InstructionIndex; } /// <summary> /// Get called from the LeaveFinallyInstruction /// </summary> public int YieldToPendingContinuation() { Debug.Assert(_pendingContinuation >= 0); RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation]; // the current continuation might have higher priority (continuationIndex is the depth of the current continuation): if (pendingTarget.ContinuationStackDepth < _continuationIndex) { RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(currentTarget.StackDepth); return currentTarget.Index - InstructionIndex; } SetStackDepth(pendingTarget.StackDepth); if (_pendingValue != Interpreter.NoValue) { Data[StackIndex - 1] = _pendingValue; } // Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; return pendingTarget.Index - InstructionIndex; } internal void PushPendingContinuation() { Push(_pendingContinuation); Push(_pendingValue); _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } internal void PopPendingContinuation() { _pendingValue = Pop(); _pendingContinuation = (int)Pop(); } public int Goto(int labelIndex, object value, bool gotoExceptionHandler) { // TODO: we know this at compile time (except for compiled loop): RuntimeLabel target = Interpreter._labels[labelIndex]; Debug.Assert(!gotoExceptionHandler || (gotoExceptionHandler && _continuationIndex == target.ContinuationStackDepth), "When it's time to jump to the exception handler, all previous finally blocks should already be processed"); if (_continuationIndex == target.ContinuationStackDepth) { SetStackDepth(target.StackDepth); if (value != Interpreter.NoValue) { Data[StackIndex - 1] = value; } return target.Index - InstructionIndex; } // if we are in the middle of executing jump we forget the previous target and replace it by a new one: _pendingContinuation = labelIndex; _pendingValue = value; return YieldToCurrentContinuation(); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MultiVideoDemo : MonoBehaviour { public GUISkin _skin; public int _guiDepth; private string _folder = string.Empty; private string _filename = string.Empty; private bool _visible = true; private float _alpha = 1.0f; private GameObject _root; private List<AVProWindowsMediaGUIDisplay> _movies; private AVProWindowsMediaGUIDisplay _activeMovie; private AVProWindowsMediaGUIDisplay _removeMovie; void Update() { Vector2 screenMouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y); // Show/Hide controls based on mouse cursor position Rect r = new Rect(0, 0, Screen.width/2, Screen.height); if (r.Contains(screenMouse)) { _visible = true; _alpha = 1.0f; } else { _alpha -= Time.deltaTime * 4f; if (_alpha <= 0.0f) { _alpha = 0.0f; _visible = false; } } // Remove any movie scheduled for removal if (_removeMovie) { Remove(_removeMovie); _removeMovie = null; } // Activate movie under mouse cursor _activeMovie = null; foreach (AVProWindowsMediaGUIDisplay gui in _movies) { Rect rect = gui.GetRect(); if (rect.Contains(screenMouse)) { gui._color = Color.white; _activeMovie = gui; } else { //gui._color = Color.white * 0.8f; gui._color = new Color(0.5f, 0.5f, 0.5f, 0.9f); } } } void Start() { _root = new GameObject("Movies"); _movies = new List<AVProWindowsMediaGUIDisplay>(); // Add some initial videos Add("Assets/AVProWindowsMedia/Demos/Shared/", "blue-480x256-divx.avi.bin"); Add("Assets/AVProWindowsMedia/Demos/Shared/", "green-480x256-divx.avi.bin"); Add("Assets/AVProWindowsMedia/Demos/Shared/", "purple-480x256-divx.avi.bin"); Add("Assets/AVProWindowsMedia/Demos/Shared/", "yellow-480x256-divx.avi.bin"); } private void Add(string folder, string filename) { GameObject go = new GameObject(); go.transform.parent = _root.transform; AVProWindowsMediaMovie movie = go.AddComponent<AVProWindowsMediaMovie>(); movie._folder = folder; movie._filename = filename; movie._loop = true; movie._loadOnStart = false; movie._playOnStart = false; AVProWindowsMediaGUIDisplay gui = go.AddComponent<AVProWindowsMediaGUIDisplay>(); gui._movie = movie; gui._scaleMode = ScaleMode.StretchToFill; gui._fullScreen = false; gui._alphaBlend = false; gui._depth = 5; gui._color = new Color(0.8f, 0.8f, 0.8f, 1.0f); _movies.Add(gui); if (!movie.LoadMovie(true)) { Remove(gui); return; } UpdateLayout(); } private void Remove(AVProWindowsMediaGUIDisplay movie) { if (movie) { _movies.Remove(movie); Destroy(movie.gameObject); UpdateLayout(); } } private void UpdateLayout() { int numMovies = _movies.Count; int numColRows = Mathf.CeilToInt(Mathf.Sqrt(numMovies)); float width = 1.0f / numColRows; float height = 1.0f / numColRows; for (int i = 0; i < numMovies; i++) { AVProWindowsMediaGUIDisplay gui = _movies[i]; int x = i % numColRows; int y = i / numColRows; gui._x = width * x; gui._y = height * y; gui._width = width; gui._height = height; } } public void ControlWindow(int id) { GUILayout.BeginVertical("box", GUILayout.MinWidth(400)); GUILayout.BeginHorizontal(); GUILayout.Label("Folder: ", GUILayout.Width(100)); _folder = GUILayout.TextField(_folder, 192); GUILayout.EndHorizontal(); GUILayout.Space(16f); GUILayout.BeginHorizontal(); GUILayout.Label("File Name: ", GUILayout.Width(100)); _filename = GUILayout.TextField(_filename, 192, GUILayout.MinWidth(256f)); if (GUILayout.Button("Add Video", GUILayout.Width(128))) { Add(_folder, _filename); } GUILayout.EndHorizontal(); GUILayout.Space(16f); if (GUILayout.Button("Remove All")) { for (int i = 0; i < _movies.Count; i++) { Destroy(_movies[i].gameObject); _movies[i] = null; } _movies.Clear(); UpdateLayout(); } GUILayout.EndVertical(); } private void DrawVideoControls(Rect area, AVProWindowsMediaGUIDisplay movieGUI) { AVProWindowsMediaMovie movie = movieGUI._movie; AVProWindowsMedia player = movie.MovieInstance; if (player == null) return; // Close button if (GUI.Button(new Rect(area.x + (area.width - 32) ,area.y, 32, 32), "X")) { _removeMovie = movieGUI; } // Duplicate button if (GUI.Button(new Rect(area.x + (area.width - 64) ,area.y, 32, 32), "+")) { Add(movie._folder, movie._filename); } // Video properties GUILayout.BeginArea(new Rect(area.x, area.y, area.width/2, area.height/2)); GUILayout.Label(player.Width + "x" + player.Height + "/" + player.FrameRate.ToString("F2") + "hz"); GUILayout.EndArea(); GUILayout.BeginArea(new Rect(area.x, area.y + (area.height - 32), area.width, 32)); GUILayout.BeginHorizontal(); float position = player.PositionSeconds; float newPosition = GUILayout.HorizontalSlider(position, 0.0f, player.DurationSeconds, GUILayout.ExpandWidth(true)); if (position != newPosition) { player.PositionSeconds = newPosition; } if (player.IsPlaying) { if (GUILayout.Button("Pause", GUILayout.ExpandWidth(false))) { player.Pause(); } } else { if (GUILayout.Button("Play", GUILayout.ExpandWidth(false))) { player.Play(); } } GUILayout.EndHorizontal(); GUILayout.EndArea(); } void OnGUI() { GUI.skin = _skin; GUI.depth = _guiDepth; if (_activeMovie) { DrawVideoControls(_activeMovie.GetRect(), _activeMovie); } if (_visible) { GUI.color = new Color(1f, 1f, 1f, _alpha); GUILayout.Box("Demo Controls"); //GUILayout.BeginArea(new Rect(0, 0, 440, 200), GUI.skin.box); ControlWindow(0); } else { GUI.color = new Color(1f, 1f, 1f, 1f - _alpha); GUI.Box(new Rect(0, 0, 128, 32), "Demo Controls"); } } }
// 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 Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.XPath; using System.Xml.Xsl; namespace System.Xml.Tests { //[TestCase(Name = "XsltSettings-Retail", Desc = "This testcase tests the different settings on XsltSettings and the corresponding behavior in retail mode", Param = "Retail")] //[TestCase(Name = "XsltSettings-Debug", Desc = "This testcase tests the different settings on XsltSettings and the corresponding behavior in debug mode", Param = "Debug")] public class CXsltSettings : XsltApiTestCaseBase2 { private ITestOutputHelper _output; public CXsltSettings(ITestOutputHelper output) : base(output) { _output = output; } private XslCompiledTransform _xsl = null; private string _xmlFile = string.Empty; private string _xslFile = string.Empty; private void Init(string xmlFile, string xslFile) { _xsl = new XslCompiledTransform(); _xmlFile = FullFilePath(xmlFile); _xslFile = FullFilePath(xslFile); } private StringWriter Transform() { StringWriter sw = new StringWriter(); _xsl.Transform(_xmlFile, null, sw); return sw; } private void VerifyResult(object actual, object expected, string message) { _output.WriteLine("Expected : {0}", expected); _output.WriteLine("Actual : {0}", actual); Assert.Equal(actual, expected); } //[Variation(id = 1, Desc = "Test the script block with EnableScript, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, true })] [InlineData(1, "XsltSettings.xml", "XsltSettings1.xsl", false, true)] //[Variation(id = 4, Desc = "Test the script block with TrustedXslt, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", true, true })] [InlineData(4, "XsltSettings.xml", "XsltSettings1.xsl", true, true)] //[Variation(id = 9, Desc = "Test the combination of script and document function with TrustedXslt, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, true })] [InlineData(9, "XsltSettings.xml", "XsltSettings3.xsl", true, true)] //[Variation(id = 11, Desc = "Test the combination of script and document function with EnableScript, only script should work", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, true })] [InlineData(11, "XsltSettings.xml", "XsltSettings3.xsl", false, true)] [Theory] public void XsltSettings1_1_ContainsScript(object param0, object param1, object param2, object param3, object param4) { var e = Assert.ThrowsAny<XsltException>(() => XsltSettings1_1(param0, param1, param2, param3, param4)); Assert.Equal("Compiling JScript/CSharp scripts is not supported", e.InnerException.Message); } //[Variation(id = 15, Desc = "Test 1 with Default settings, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, true, false, false })] [InlineData(15, "XsltSettings.xml", "XsltSettings1.xsl", false, true, false, false)] //[Variation(id = 16, Desc = "Test 2 with EnableScript override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, false, false, true })] [InlineData(16, "XsltSettings.xml", "XsltSettings1.xsl", false, false, false, true)] //[Variation(id = 19, Desc = "Test 9 with Default settings override, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, true, false, false })] [InlineData(19, "XsltSettings.xml", "XsltSettings3.xsl", true, true, false, false)] //[Variation(id = 20, Desc = "Test 10 with TrustedXslt override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, false, true, true })] [InlineData(20, "XsltSettings.xml", "XsltSettings3.xsl", false, false, true, true)] [Theory] public void XsltSettings1_2_ContainsScript(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { var e = Assert.ThrowsAny<XsltException>(() => XsltSettings1_2(param0, param1, param2, param3, param4, param5, param6)); Assert.Equal("Compiling JScript/CSharp scripts is not supported", e.InnerException.Message); } //[Variation(id = 5, Desc = "Test the document function with EnableDocumentFunction, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, false })] [InlineData(5, "XsltSettings.xml", "XsltSettings2.xsl", true, false)] //[Variation(id = 8, Desc = "Test the document function with TrustedXslt, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, true })] [InlineData(8, "XsltSettings.xml", "XsltSettings2.xsl", true, true)] [Theory] public void XsltSettings1_1_ExternalURI(object param0, object param1, object param2, object param3, object param4) { AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true); XsltSettings1_1(param0, param1, param2, param3, param4); } //[Variation(id = 18, Desc = "Test 6 with EnableDocumentFunction override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, false, true, false })] [InlineData(18, "XsltSettings.xml", "XsltSettings2.xsl", false, false, true, false)] [Theory] public void XsltSettings1_2_ExternalURI(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true); XsltSettings1_2(param0, param1, param2, param3, param4, param5, param6); } //[Variation(id = 2, Desc = "Test the script block with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, false })] [InlineData(2, "XsltSettings.xml", "XsltSettings1.xsl", false, false)] //[Variation(id = 3, Desc = "Test the script block with EnableDocumentFunction, should fail", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", true, false })] [InlineData(3, "XsltSettings.xml", "XsltSettings1.xsl", true, false)] //[Variation(id = 6, Desc = "Test the document function with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, false })] [InlineData(6, "XsltSettings.xml", "XsltSettings2.xsl", false, false)] //[Variation(id = 7, Desc = "Test the document function with EnableScript, should fail", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, true })] [InlineData(7, "XsltSettings.xml", "XsltSettings2.xsl", false, true)] //[Variation(id = 10, Desc = "Test the combination of script and document function with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, false })] [InlineData(10, "XsltSettings.xml", "XsltSettings3.xsl", false, false)] //[Variation(id = 12, Desc = "Test the combination of script and document function with EnableDocumentFunction, only document should work", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, false })] [InlineData(12, "XsltSettings.xml", "XsltSettings3.xsl", true, false)] //[Variation(id = 13, Desc = "Test the stylesheet with no script and document function with Default Settings", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings4.xsl", false, false })] [InlineData(13, "XsltSettings.xml", "XsltSettings4.xsl", false, false)] //[Variation(id = 14, Desc = "Test the stylesheet with no script and document function with TrustedXslt", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings4.xsl", true, true })] [InlineData(14, "XsltSettings.xml", "XsltSettings4.xsl", true, true)] /* * enable all disable scripting * enable all disable document() * enable all disable none * enable all disable all */ [Theory] public void XsltSettings1_1(object param0, object param1, object param2, object param3, object param4) { Init(param1.ToString(), param2.ToString()); // In Proc Skip // XsltSettings - Debug (1-20) // XsltSettings - Retail (1,4,9,11,15,16,19,20) XsltSettings xs = new XsltSettings((bool)param3, (bool)param4); _xsl.Load(_xslFile, xs, new XmlUrlResolver()); try { StringWriter sw = Transform(); switch ((int)param0) { case 1: case 4: VerifyResult(sw.ToString(), "30", "Unexpected result, expected 30"); return; case 5: case 8: VerifyResult(sw.ToString(), "7", "Unexpected result, expected 7"); return; case 9: VerifyResult(sw.ToString(), "17", "Unexpected result, expected 17"); return; case 13: case 14: VerifyResult(sw.ToString(), "PASS", "Unexpected result, expected PASS"); return; default: Assert.True(false); return; } } catch (XsltException ex) { switch ((int)param0) { case 2: case 3: case 6: case 7: case 10: case 11: case 12: _output.WriteLine(ex.ToString()); _output.WriteLine(ex.Message); return; default: Assert.True(false); return; } } } //[Variation(id = 17, Desc = "Test 5 with Default settings override, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, false, false, false })] [InlineData(17, "XsltSettings.xml", "XsltSettings2.xsl", true, false, false, false)] /* * enable all disable scripting * enable all disable document() * enable all disable none * enable all disable all */ [Theory] public void XsltSettings1_2(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { Init(param1.ToString(), param2.ToString()); XsltSettings xs = new XsltSettings((bool)param3, (bool)param4); _xsl.Load(_xslFile, xs, new XmlUrlResolver()); xs.EnableDocumentFunction = (bool)param5; xs.EnableScript = (bool)param6; _xsl.Load(_xslFile, xs, new XmlUrlResolver()); try { StringWriter sw = Transform(); switch ((int)param0) { case 16: VerifyResult(sw.ToString(), "30", "Unexpected result, expected 30"); return; case 18: VerifyResult(sw.ToString(), "7", "Unexpected result, expected 7"); return; case 20: VerifyResult(sw.ToString(), "17", "Unexpected result, expected 17"); return; default: Assert.True(false); return; } } catch (XsltException ex) { switch ((int)param0) { case 15: case 17: case 19: _output.WriteLine(ex.ToString()); _output.WriteLine(ex.Message); return; default: Assert.True(false); return; } } } //[Variation(id = 21, Desc = "Disable Scripting and load a stylesheet which includes another sytlesheet with script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings5.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings5.xsl", false, false)] //[Variation(id = 22, Desc = "Disable Scripting and load a stylesheet which imports XSLT which includes another XSLT with script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings6.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings6.xsl", false, false)] //[Variation(id = 23, Desc = "Disable Scripting and load a stylesheet which has an entity expanding to a script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings7.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings7.xsl", false, false)] //[Variation(id = 24, Desc = "Disable Scripting and load a stylesheet with multiple script blocks with different languages", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings8.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings8.xsl", false, false)] [Theory] public void XsltSettings2(object param0, object param1, object param2, object param3) { Init(param0.ToString(), param1.ToString()); XsltSettings xs = new XsltSettings((bool)param2, (bool)param3); XPathDocument doc = new XPathDocument(_xslFile); _xsl.Load(doc, xs, new XmlUrlResolver()); try { StringWriter sw = Transform(); _output.WriteLine("Execution of the scripts was allowed even when XsltSettings.EnableScript is false"); Assert.True(false); } catch (XsltException ex) { _output.WriteLine(ex.ToString()); return; } } //[Variation(id = 25, Desc = "Disable DocumentFunction and Malicious stylesheet has document(url) opening a URL to an external system", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings9.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings9.xsl", false, false)] //[Variation(id = 26, Desc = "Disable DocumentFunction and Malicious stylesheet has document(nodeset) opens union of all URLs referenced", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings10.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings10.xsl", false, false)] //[Variation(id = 27, Desc = "Disable DocumentFunction and Malicious stylesheet has document(url, nodeset) nodeset is a base URL to 1st arg", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings11.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings11.xsl", false, false)] //[Variation(id = 28, Desc = "Disable DocumentFunction and Malicious stylesheet has document(nodeset, nodeset) 2nd arg is a base URL to 1st arg", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings12.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings12.xsl", false, false)] //[Variation(id = 29, Desc = "Disable DocumentFunction and Malicious stylesheet has document(''), no threat but just to verify if its considered", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings13.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings13.xsl", false, false)] //[Variation(id = 30, Desc = "Disable DocumentFunction and Stylesheet includes another stylesheet with document() function", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings14.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings14.xsl", false, false)] //[Variation(id = 31, Desc = "Disable DocumentFunction and Stylesheet has an entity reference to doc(), ENTITY s document('foo.xml')", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings15.xsl", false, false })] [InlineData("XsltSettings.xml", "XsltSettings15.xsl", false, false)] [Theory] public void XsltSettings3(object param0, object param1, object param2, object param3) { Init(param0.ToString(), param1.ToString()); XsltSettings xs = new XsltSettings((bool)param2, (bool)param3); XPathDocument doc = new XPathDocument(_xslFile); _xsl.Load(doc, xs, new XmlUrlResolver()); StringWriter sw; var e = Assert.ThrowsAny<XsltException>(() => sw = Transform()); Assert.Contains("Execution of the 'document()' function was prohibited. Use the XsltSettings.EnableDocumentFunction property to enable it.", e.Message); } } }
// *********************************************************************** // Copyright (c) 2008-2012 Charlie Poole // // 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.Reflection; using NUnit.Framework.Api; using NUnit.Framework.Internal; using NUnit.Framework.Extensibility; using NUnit.Framework.Internal.Commands; #if NET_4_5 using System.Threading.Tasks; #endif namespace NUnit.Framework.Builders { /// <summary> /// Class to build ether a parameterized or a normal NUnitTestMethod. /// There are four cases that the builder must deal with: /// 1. The method needs no params and none are provided /// 2. The method needs params and they are provided /// 3. The method needs no params but they are provided in error /// 4. The method needs params but they are not provided /// This could have been done using two different builders, but it /// turned out to be simpler to have just one. The BuildFrom method /// takes a different branch depending on whether any parameters are /// provided, but all four cases are dealt with in lower-level methods /// </summary> public class NUnitTestCaseBuilder : ITestCaseBuilder2 { private Randomizer random; #if NUNITLITE private ITestCaseProvider testCaseProvider = new TestCaseProviders(); #else private ITestCaseProvider testCaseProvider = CoreExtensions.Host.TestCaseProviders; #endif /// <summary> /// Default no argument constructor for NUnitTestCaseBuilder /// </summary> public NUnitTestCaseBuilder() { //MethodBase.GetCurrentMethod does not compile on NETCF so this method is used instead random = Randomizer.GetRandomizer(typeof(NUnitTestCaseBuilder).GetConstructor(new Type[0])); } #region ITestCaseBuilder Methods /// <summary> /// Determines if the method can be used to build an NUnit test /// test method of some kind. The method must normally be marked /// with an identifying attriute for this to be true. /// /// Note that this method does not check that the signature /// of the method for validity. If we did that here, any /// test methods with invalid signatures would be passed /// over in silence in the test run. Since we want such /// methods to be reported, the check for validity is made /// in BuildFrom rather than here. /// </summary> /// <param name="method">A MethodInfo for the method being used as a test method</param> /// <returns>True if the builder can create a test case from this method</returns> public bool CanBuildFrom(MethodInfo method) { return method.IsDefined(typeof(TestAttribute), false) || method.IsDefined(typeof(ITestCaseSource), false) || method.IsDefined(typeof(TheoryAttribute), false); } /// <summary> /// Build a Test from the provided MethodInfo. Depending on /// whether the method takes arguments and on the availability /// of test case data, this method may return a single test /// or a group of tests contained in a ParameterizedMethodSuite. /// </summary> /// <param name="method">The MethodInfo for which a test is to be built</param> /// <returns>A Test representing one or more method invocations</returns> public Test BuildFrom(MethodInfo method) { return BuildFrom(method, null); } #endregion #region ITestCaseBuilder2 Members /// <summary> /// Determines if the method can be used to build an NUnit test /// test method of some kind. The method must normally be marked /// with an identifying attriute for this to be true. /// /// Note that this method does not check that the signature /// of the method for validity. If we did that here, any /// test methods with invalid signatures would be passed /// over in silence in the test run. Since we want such /// methods to be reported, the check for validity is made /// in BuildFrom rather than here. /// </summary> /// <param name="method">A MethodInfo for the method being used as a test method</param> /// <param name="parentSuite">The test suite being built, to which the new test would be added</param> /// <returns>True if the builder can create a test case from this method</returns> public bool CanBuildFrom(MethodInfo method, Test parentSuite) { return CanBuildFrom(method); } /// <summary> /// Build a Test from the provided MethodInfo. Depending on /// whether the method takes arguments and on the availability /// of test case data, this method may return a single test /// or a group of tests contained in a ParameterizedMethodSuite. /// </summary> /// <param name="method">The MethodInfo for which a test is to be built</param> /// <param name="parentSuite">The test fixture being populated, or null</param> /// <returns>A Test representing one or more method invocations</returns> public Test BuildFrom(MethodInfo method, Test parentSuite) { return testCaseProvider.HasTestCasesFor(method) ? BuildParameterizedMethodSuite(method, parentSuite) : BuildSingleTestMethod(method, parentSuite, null); } #endregion #region Implementation /// <summary> /// Builds a ParameterizedMetodSuite containing individual /// test cases for each set of parameters provided for /// this method. /// </summary> /// <param name="method">The MethodInfo for which a test is to be built</param> /// <param name="parentSuite">The test suite for which the method is being built</param> /// <returns>A ParameterizedMethodSuite populated with test cases</returns> public Test BuildParameterizedMethodSuite(MethodInfo method, Test parentSuite) { ParameterizedMethodSuite methodSuite = new ParameterizedMethodSuite(method); methodSuite.ApplyAttributesToTest(method); foreach (ITestCaseData testcase in testCaseProvider.GetTestCasesFor(method)) { ParameterSet parms = testcase as ParameterSet; if (parms == null) parms = new ParameterSet(testcase); TestMethod test = BuildSingleTestMethod(method, parentSuite, parms); methodSuite.Add(test); } return methodSuite; } /// <summary> /// Builds a single NUnitTestMethod, either as a child of the fixture /// or as one of a set of test cases under a ParameterizedTestMethodSuite. /// </summary> /// <param name="method">The MethodInfo from which to construct the TestMethod</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> /// <param name="parms">The ParameterSet to be used, or null</param> /// <returns></returns> private TestMethod BuildSingleTestMethod(MethodInfo method, Test parentSuite, ParameterSet parms) { TestMethod testMethod = new TestMethod(method, parentSuite); testMethod.Seed = random.Next(); string prefix = method.ReflectedType.FullName; // Needed to give proper fullname to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. if (parentSuite != null) { prefix = parentSuite.FullName; //testMethod.FullName = prefix + "." + testMethod.Name; } if (CheckTestMethodSignature(testMethod, parms)) { if (parms == null) testMethod.ApplyAttributesToTest(method); foreach (ICommandDecorator decorator in method.GetCustomAttributes(typeof(ICommandDecorator), true)) testMethod.CustomDecorators.Add(decorator); ExpectedExceptionAttribute[] attributes = (ExpectedExceptionAttribute[])method.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false); if (attributes.Length > 0) { ExpectedExceptionAttribute attr = attributes[0]; string handlerName = attr.Handler; if (handlerName != null && GetExceptionHandler(testMethod.FixtureType, handlerName) == null) MarkAsNotRunnable( testMethod, string.Format("The specified exception handler {0} was not found", handlerName)); testMethod.CustomDecorators.Add(new ExpectedExceptionDecorator(attr.ExceptionData)); } } if (parms != null) { // NOTE: After the call to CheckTestMethodSignature, the Method // property of testMethod may no longer be the same as the // original MethodInfo, so we reassign it here. method = testMethod.Method; if (parms.TestName != null) { testMethod.Name = parms.TestName; testMethod.FullName = prefix + "." + parms.TestName; } else if (parms.OriginalArguments != null) { string name = MethodHelper.GetDisplayName(method, parms.OriginalArguments); testMethod.Name = name; testMethod.FullName = prefix + "." + name; } parms.ApplyToTest(testMethod); } return testMethod; } #endregion #region Helper Methods /// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> private static bool CheckTestMethodSignature(TestMethod testMethod, ParameterSet parms) { if (testMethod.Method.IsAbstract) { return MarkAsNotRunnable(testMethod, "Method is abstract"); } if (!testMethod.Method.IsPublic) { return MarkAsNotRunnable(testMethod, "Method is not public"); } #if NETCF // TODO: Get this to work if (testMethod.Method.IsGenericMethodDefinition) { return MarkAsNotRunnable(testMethod, "Generic test methods are not yet supported under .NET CF"); } #endif ParameterInfo[] parameters = testMethod.Method.GetParameters(); int argsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } Type returnType = testMethod.Method.ReturnType; if (returnType.Equals(typeof(void))) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); } else { #if NET_4_5 if (MethodHelper.IsAsyncMethod(testMethod.Method)) { bool returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>); if (returnsGenericTask && (parms == null|| !parms.HasExpectedResult && !parms.ExceptionExpected)) return MarkAsNotRunnable(testMethod, "Async test method must have Task or void return type when no result is expected"); else if (!returnsGenericTask && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected"); } else #endif if (parms == null || !parms.HasExpectedResult && !parms.ExceptionExpected) return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); } if (argsProvided > 0 && argsNeeded == 0) { return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any"); } if (argsProvided == 0 && argsNeeded > 0) { return MarkAsNotRunnable(testMethod, "No arguments were provided"); } if (argsProvided != argsNeeded) { return MarkAsNotRunnable(testMethod, "Wrong number of arguments provided"); } #if CLR_2_0 || CLR_4_0 #if !NETCF if (testMethod.Method.IsGenericMethodDefinition) { Type[] typeArguments = GetTypeArgumentsForMethod(testMethod.Method, arglist); foreach (object o in typeArguments) if (o == null) { return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); } testMethod.method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } #endif #endif if (arglist != null && parameters != null) TypeHelper.ConvertArgumentList(arglist, parameters); return true; } #if CLR_2_0 || CLR_4_0 #if !NETCF private static Type[] GetTypeArgumentsForMethod(MethodInfo method, object[] arglist) { Type[] typeParameters = method.GetGenericArguments(); Type[] typeArguments = new Type[typeParameters.Length]; ParameterInfo[] parameters = method.GetParameters(); for (int typeIndex = 0; typeIndex < typeArguments.Length; typeIndex++) { Type typeParameter = typeParameters[typeIndex]; for (int argIndex = 0; argIndex < parameters.Length; argIndex++) { if (parameters[argIndex].ParameterType.Equals(typeParameter)) typeArguments[typeIndex] = TypeHelper.BestCommonType( typeArguments[typeIndex], arglist[argIndex].GetType()); } } return typeArguments; } #endif #endif private static MethodInfo GetExceptionHandler(Type fixtureType, string name) { return fixtureType.GetMethod( name, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(System.Exception) }, null); } private static bool MarkAsNotRunnable(TestMethod testMethod, string reason) { testMethod.RunState = RunState.NotRunnable; testMethod.Properties.Set(PropertyNames.SkipReason, reason); return false; } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Microsoft.Azure.Management.Automation; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; namespace Microsoft.Azure.Management.Automation { public partial class AutomationManagementClient : ServiceClient<AutomationManagementClient>, IAutomationManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private ICloudServiceOperations _cloudServices; /// <summary> /// Definition of cloud service for the automation extension. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual ICloudServiceOperations CloudServices { get { return this._cloudServices; } } private IJobOperations _jobs; /// <summary> /// Service operation for automation jobs. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IJobOperations Jobs { get { return this._jobs; } } private IJobStreamOperation _jobStreams; /// <summary> /// Service operation for automation stream items. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IJobStreamOperation JobStreams { get { return this._jobStreams; } } private IRunbookOperations _runbooks; /// <summary> /// Service operation for automation runbooks. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IRunbookOperations Runbooks { get { return this._runbooks; } } private IRunbookParameterOperations _runbookParameters; /// <summary> /// Service operation for automation runbook parameters. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IRunbookParameterOperations RunbookParameters { get { return this._runbookParameters; } } private IRunbookVersionOperations _runbookVersions; /// <summary> /// Service operation for automation runbook versions. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IRunbookVersionOperations RunbookVersions { get { return this._runbookVersions; } } private IScheduleOperations _schedules; /// <summary> /// Service operation for automation schedules. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> public virtual IScheduleOperations Schedules { get { return this._schedules; } } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> private AutomationManagementClient() : base() { this._cloudServices = new CloudServiceOperations(this); this._jobs = new JobOperations(this); this._jobStreams = new JobStreamOperation(this); this._runbooks = new RunbookOperations(this); this._runbookParameters = new RunbookParameterOperations(this); this._runbookVersions = new RunbookVersionOperations(this); this._schedules = new ScheduleOperations(this); this._apiVersion = "2013-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public AutomationManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private AutomationManagementClient(HttpClient httpClient) : base(httpClient) { this._cloudServices = new CloudServiceOperations(this); this._jobs = new JobOperations(this); this._jobStreams = new JobStreamOperation(this); this._runbooks = new RunbookOperations(this); this._runbookParameters = new RunbookParameterOperations(this); this._runbookVersions = new RunbookVersionOperations(this); this._schedules = new ScheduleOperations(this); this._apiVersion = "2013-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutomationManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AutomationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// AutomationManagementClient instance /// </summary> /// <param name='client'> /// Instance of AutomationManagementClient to clone to /// </param> protected override void Clone(ServiceClient<AutomationManagementClient> client) { base.Clone(client); if (client is AutomationManagementClient) { AutomationManagementClient clonedClient = ((AutomationManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
using System; using ChainUtils.BouncyCastle.Crypto.Parameters; namespace ChainUtils.BouncyCastle.Crypto.Engines { /** * an implementation of Rijndael, based on the documentation and reference implementation * by Paulo Barreto, Vincent Rijmen, for v2.0 August '99. * <p> * Note: this implementation is based on information prior to readonly NIST publication. * </p> */ public class RijndaelEngine : IBlockCipher { private static readonly int MAXROUNDS = 14; private static readonly int MAXKC = (256/4); private static readonly byte[] Logtable = { 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 }; private static readonly byte[] Alogtable = { 0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, }; private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; static readonly byte[][] shifts0 = new byte [][] { new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 32 }, new byte[]{ 0, 8, 24, 32 } }; static readonly byte[][] shifts1 = { new byte[]{ 0, 24, 16, 8 }, new byte[]{ 0, 32, 24, 16 }, new byte[]{ 0, 40, 32, 24 }, new byte[]{ 0, 48, 40, 24 }, new byte[]{ 0, 56, 40, 32 } }; /** * multiply two elements of GF(2^m) * needed for MixColumn and InvMixColumn */ private byte Mul0x2( int b) { if (b != 0) { return Alogtable[25 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x3( int b) { if (b != 0) { return Alogtable[1 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x9( int b) { if (b >= 0) { return Alogtable[199 + b]; } else { return 0; } } private byte Mul0xb( int b) { if (b >= 0) { return Alogtable[104 + b]; } else { return 0; } } private byte Mul0xd( int b) { if (b >= 0) { return Alogtable[238 + b]; } else { return 0; } } private byte Mul0xe( int b) { if (b >= 0) { return Alogtable[223 + b]; } else { return 0; } } /** * xor corresponding text input and round key input bytes */ private void KeyAddition( long[] rk) { A0 ^= rk[0]; A1 ^= rk[1]; A2 ^= rk[2]; A3 ^= rk[3]; } private long Shift( long r, int shift) { //return (((long)((ulong) r >> shift) | (r << (BC - shift)))) & BC_MASK; var temp = (ulong) r >> shift; // NB: This corrects for Mono Bug #79087 (fixed in 1.1.17) if (shift > 31) { temp &= 0xFFFFFFFFUL; } return ((long) temp | (r << (BC - shift))) & BC_MASK; } /** * Row 0 remains unchanged * The other three rows are shifted a variable amount */ private void ShiftRow( byte[] shiftsSC) { A1 = Shift(A1, shiftsSC[1]); A2 = Shift(A2, shiftsSC[2]); A3 = Shift(A3, shiftsSC[3]); } private long ApplyS( long r, byte[] box) { long res = 0; for (var j = 0; j < BC; j += 8) { res |= (long)(box[(int)((r >> j) & 0xff)] & 0xff) << j; } return res; } /** * Replace every byte of the input by the byte at that place * in the nonlinear S-box */ private void Substitution( byte[] box) { A0 = ApplyS(A0, box); A1 = ApplyS(A1, box); A2 = ApplyS(A2, box); A3 = ApplyS(A3, box); } /** * Mix the bytes of every column in a linear way */ private void MixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (var j = 0; j < BC; j += 8) { var a0 = (int)((A0 >> j) & 0xff); var a1 = (int)((A1 >> j) & 0xff); var a2 = (int)((A2 >> j) & 0xff); var a3 = (int)((A3 >> j) & 0xff); r0 |= (long)((Mul0x2(a0) ^ Mul0x3(a1) ^ a2 ^ a3) & 0xff) << j; r1 |= (long)((Mul0x2(a1) ^ Mul0x3(a2) ^ a3 ^ a0) & 0xff) << j; r2 |= (long)((Mul0x2(a2) ^ Mul0x3(a3) ^ a0 ^ a1) & 0xff) << j; r3 |= (long)((Mul0x2(a3) ^ Mul0x3(a0) ^ a1 ^ a2) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Mix the bytes of every column in a linear way * This is the opposite operation of Mixcolumn */ private void InvMixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (var j = 0; j < BC; j += 8) { var a0 = (int)((A0 >> j) & 0xff); var a1 = (int)((A1 >> j) & 0xff); var a2 = (int)((A2 >> j) & 0xff); var a3 = (int)((A3 >> j) & 0xff); // // pre-lookup the log table // a0 = (a0 != 0) ? (Logtable[a0 & 0xff] & 0xff) : -1; a1 = (a1 != 0) ? (Logtable[a1 & 0xff] & 0xff) : -1; a2 = (a2 != 0) ? (Logtable[a2 & 0xff] & 0xff) : -1; a3 = (a3 != 0) ? (Logtable[a3 & 0xff] & 0xff) : -1; r0 |= (long)((Mul0xe(a0) ^ Mul0xb(a1) ^ Mul0xd(a2) ^ Mul0x9(a3)) & 0xff) << j; r1 |= (long)((Mul0xe(a1) ^ Mul0xb(a2) ^ Mul0xd(a3) ^ Mul0x9(a0)) & 0xff) << j; r2 |= (long)((Mul0xe(a2) ^ Mul0xb(a3) ^ Mul0xd(a0) ^ Mul0x9(a1)) & 0xff) << j; r3 |= (long)((Mul0xe(a3) ^ Mul0xb(a0) ^ Mul0xd(a1) ^ Mul0x9(a2)) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Calculate the necessary round keys * The number of calculations depends on keyBits and blockBits */ private long[][] GenerateWorkingKey( byte[] key) { int KC; int t, rconpointer = 0; var keyBits = key.Length * 8; var tk = new byte[4,MAXKC]; //long[,] W = new long[MAXROUNDS+1,4]; var W = new long[MAXROUNDS+1][]; for (var i = 0; i < MAXROUNDS+1; i++) W[i] = new long[4]; switch (keyBits) { case 128: KC = 4; break; case 160: KC = 5; break; case 192: KC = 6; break; case 224: KC = 7; break; case 256: KC = 8; break; default : throw new ArgumentException("Key length not 128/160/192/224/256 bits."); } if (keyBits >= blockBits) { ROUNDS = KC + 6; } else { ROUNDS = (BC / 8) + 6; } // // copy the key into the processing area // var index = 0; for (var i = 0; i < key.Length; i++) { tk[i % 4,i / 4] = key[index++]; } t = 0; // // copy values into round key array // for (var j = 0; (j < KC) && (t < (ROUNDS+1)*(BC / 8)); j++, t++) { for (var i = 0; i < 4; i++) { W[t / (BC / 8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % BC); } } // // while not enough round key material calculated // calculate new values // while (t < (ROUNDS+1)*(BC/8)) { for (var i = 0; i < 4; i++) { tk[i,0] ^= S[tk[(i+1)%4,KC-1] & 0xff]; } tk[0,0] ^= (byte) rcon[rconpointer++]; if (KC <= 6) { for (var j = 1; j < KC; j++) { for (var i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } else { for (var j = 1; j < 4; j++) { for (var i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } for (var i = 0; i < 4; i++) { tk[i,4] ^= S[tk[i,3] & 0xff]; } for (var j = 5; j < KC; j++) { for (var i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } // // copy values into round key array // for (var j = 0; (j < KC) && (t < (ROUNDS+1)*(BC/8)); j++, t++) { for (var i = 0; i < 4; i++) { W[t / (BC/8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % (BC)); } } } return W; } private int BC; private long BC_MASK; private int ROUNDS; private int blockBits; private long[][] workingKey; private long A0, A1, A2, A3; private bool forEncryption; private byte[] shifts0SC; private byte[] shifts1SC; /** * default constructor - 128 bit block size. */ public RijndaelEngine() : this(128) {} /** * basic constructor - set the cipher up for a given blocksize * * @param blocksize the blocksize in bits, must be 128, 192, or 256. */ public RijndaelEngine( int blockBits) { switch (blockBits) { case 128: BC = 32; BC_MASK = 0xffffffffL; shifts0SC = shifts0[0]; shifts1SC = shifts1[0]; break; case 160: BC = 40; BC_MASK = 0xffffffffffL; shifts0SC = shifts0[1]; shifts1SC = shifts1[1]; break; case 192: BC = 48; BC_MASK = 0xffffffffffffL; shifts0SC = shifts0[2]; shifts1SC = shifts1[2]; break; case 224: BC = 56; BC_MASK = 0xffffffffffffffL; shifts0SC = shifts0[3]; shifts1SC = shifts1[3]; break; case 256: BC = 64; BC_MASK = unchecked( (long)0xffffffffffffffffL); shifts0SC = shifts0[4]; shifts1SC = shifts1[4]; break; default: throw new ArgumentException("unknown blocksize to Rijndael"); } this.blockBits = blockBits; } /** * initialise a Rijndael cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (typeof(KeyParameter).IsInstanceOfType(parameters)) { workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey()); this.forEncryption = forEncryption; return; } throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString()); } public string AlgorithmName { get { return "Rijndael"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BC / 2; } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) { throw new InvalidOperationException("Rijndael engine not initialised"); } if ((inOff + (BC / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (BC / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(workingKey); } else { DecryptBlock(workingKey); } PackBlock(output, outOff); return BC / 2; } public void Reset() { } private void UnPackBlock( byte[] bytes, int off) { var index = off; A0 = (long)(bytes[index++] & 0xff); A1 = (long)(bytes[index++] & 0xff); A2 = (long)(bytes[index++] & 0xff); A3 = (long)(bytes[index++] & 0xff); for (var j = 8; j != BC; j += 8) { A0 |= (long)(bytes[index++] & 0xff) << j; A1 |= (long)(bytes[index++] & 0xff) << j; A2 |= (long)(bytes[index++] & 0xff) << j; A3 |= (long)(bytes[index++] & 0xff) << j; } } private void PackBlock( byte[] bytes, int off) { var index = off; for (var j = 0; j != BC; j += 8) { bytes[index++] = (byte)(A0 >> j); bytes[index++] = (byte)(A1 >> j); bytes[index++] = (byte)(A2 >> j); bytes[index++] = (byte)(A3 >> j); } } private void EncryptBlock( long[][] rk) { int r; // // begin with a key addition // KeyAddition(rk[0]); // // ROUNDS-1 ordinary rounds // for (r = 1; r < ROUNDS; r++) { Substitution(S); ShiftRow(shifts0SC); MixColumn(); KeyAddition(rk[r]); } // // Last round is special: there is no MixColumn // Substitution(S); ShiftRow(shifts0SC); KeyAddition(rk[ROUNDS]); } private void DecryptBlock( long[][] rk) { int r; // To decrypt: apply the inverse operations of the encrypt routine, // in opposite order // // (KeyAddition is an involution: it 's equal to its inverse) // (the inverse of Substitution with table S is Substitution with the inverse table of S) // (the inverse of Shiftrow is Shiftrow over a suitable distance) // // First the special round: // without InvMixColumn // with extra KeyAddition // KeyAddition(rk[ROUNDS]); Substitution(Si); ShiftRow(shifts1SC); // // ROUNDS-1 ordinary rounds // for (r = ROUNDS-1; r > 0; r--) { KeyAddition(rk[r]); InvMixColumn(); Substitution(Si); ShiftRow(shifts1SC); } // // End with the extra key addition // KeyAddition(rk[0]); } } }
// 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; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = String.Empty; foreach(var arg in args) { if (sargs != String.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Diagnostics.Contracts.Internal { internal class Contract { public static void Assert(bool invariant) { Assert(invariant, string.Empty); } public static void Assert(bool invariant, string message) { if (!invariant) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); throw new Exception("Assertion failed: " + message); } } public static void EndContractBlock() { } } } namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if (ES_BUILD_PCL || PROJECTN) [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif static class ReflectionExtensions { #if (!ES_BUILD_PCL && !PROJECTN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { return type.GetRuntimeProperties(); } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(Decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL || PROJECTN namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if PROJECTN namespace System { public static class AppDomain { public static int GetCurrentThreadId() { return (int)Interop.mincore.GetCurrentThreadId(); } } } #endif
using Moritz.Xml; namespace Moritz.Symbols { public abstract class Beam { /// <summary> /// Creates a horizontal Beam whose top edge is at 0F. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="y"></param> public Beam(float left, float right) { LeftX = left; RightX = right; _leftTopY = 0F; _rightTopY = 0F; } public void MoveYs(float dLeftY, float dRightY) { _leftTopY += dLeftY; _rightTopY += dRightY; } public abstract void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness); /// <summary> /// Shifts a horizontal beam vertically to the correct position (wrt the beamBlock) for its duration class /// </summary> /// <param name="outerLeftY"></param> /// <param name="gap"></param> /// <param name="stemDirection"></param> /// <param name="beamThickness"></param> /// <param name="nGaps"></param> protected void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness, int nGaps) { float dy = 0F; if(stemDirection == VerticalDir.down) { dy = -(beamThickness + (gap * nGaps)); } else { dy = gap * nGaps; } dy += outerLeftY - _leftTopY ; MoveYs(dy, dy); } /// <summary> /// Exposed as public function by each IBeamStub /// </summary> protected void ShearStub(float shearAxis, float tanAlpha, float stemX) { if(LeftX == stemX || RightX == stemX) { float dLeftY = (LeftX - shearAxis) * tanAlpha; float dRightY = (RightX - shearAxis) * tanAlpha; MoveYs(dLeftY, dRightY); } // else do nothing } public readonly float LeftX; public readonly float RightX; public readonly float StrokeWidth; public float LeftTopY { get { return _leftTopY; } } public float RightTopY { get { return _rightTopY; } } protected float _leftTopY; protected float _rightTopY; } internal class QuaverBeam : Beam { public QuaverBeam(float left, float right) : base(left, right) { } public override void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness) { ShiftYsForBeamBlock(outerLeftY, gap, stemDirection, beamThickness, 0); } } internal class SemiquaverBeam : Beam { public SemiquaverBeam(float left, float right) : base(left, right) { } public override void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness) { ShiftYsForBeamBlock(outerLeftY, gap, stemDirection, beamThickness, 1); } } internal class ThreeFlagsBeam : Beam { public ThreeFlagsBeam(float left, float right) : base(left, right) { } public override void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness) { ShiftYsForBeamBlock(outerLeftY, gap, stemDirection, beamThickness, 2); } } internal class FourFlagsBeam : Beam { public FourFlagsBeam(float left, float right) : base(left, right) { } public override void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness) { ShiftYsForBeamBlock(outerLeftY, gap, stemDirection, beamThickness, 3); } } internal class FiveFlagsBeam : Beam { public FiveFlagsBeam(float left, float right) : base(left, right) { } public override void ShiftYsForBeamBlock(float outerLeftY, float gap, VerticalDir stemDirection, float beamThickness) { ShiftYsForBeamBlock(outerLeftY, gap, stemDirection, beamThickness, 4); } } /**********************************************************************************************/ public interface IBeamStub { DurationClass DurationClass { get; } void ShearBeamStub(float shearAxis, float tanAlpha, float stemX); } internal class SemiquaverBeamStub : SemiquaverBeam, IBeamStub { public SemiquaverBeamStub(float left, float right) : base(left, right) { } public void ShearBeamStub(float shearAxis, float tanAlpha, float stemX) { base.ShearStub(shearAxis, tanAlpha, stemX); } public DurationClass DurationClass { get { return DurationClass.semiquaver; } } } internal class ThreeFlagsBeamStub : ThreeFlagsBeam, IBeamStub { public ThreeFlagsBeamStub(float left, float right) : base(left, right) { } public void ShearBeamStub(float shearAxis, float tanAlpha, float stemX) { base.ShearStub(shearAxis, tanAlpha, stemX); } public DurationClass DurationClass { get { return DurationClass.threeFlags; } } } internal class FourFlagsBeamStub : FourFlagsBeam, IBeamStub { public FourFlagsBeamStub(float left, float right) : base(left, right) { } public void ShearBeamStub(float shearAxis, float tanAlpha, float stemX) { base.ShearStub(shearAxis, tanAlpha, stemX); } public DurationClass DurationClass { get { return DurationClass.fourFlags; } } } internal class FiveFlagsBeamStub : FiveFlagsBeam, IBeamStub { public FiveFlagsBeamStub(float left, float right) : base(left, right) { } public void ShearBeamStub(float shearAxis, float tanAlpha, float stemX) { base.ShearStub(shearAxis, tanAlpha, stemX); } public DurationClass DurationClass { get { return DurationClass.fiveFlags; } } } }
//------------------------------------------------------------------------------ // Microsoft Windows Presentation Foudnation // Copyright (c) Microsoft Corporation, 2009 // // File: BitmapCacheBrush.cs //------------------------------------------------------------------------------ using System.Diagnostics; using System.Windows; using System.Windows.Threading; using System.Windows.Media.Media3D; using System.Windows.Media.Composition; using System.Windows.Media.Animation; using System.Security; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media { public partial class BitmapCacheBrush : Brush, ICyclicBrush { #region Constructors public BitmapCacheBrush() { } /// <summary> /// VisualBrush Constructor where the image is set to the parameter's value /// </summary> /// <param name="visual"> The Visual representing the contents of this Brush. </param> public BitmapCacheBrush(Visual visual) { if (this.Dispatcher != null) { MediaSystem.AssertSameContext(this, visual); Target = visual; } } #endregion Constructors private ContainerVisual AutoWrapVisual { get { // Lazily create the dummy visual instance. if (_dummyVisual == null) { _dummyVisual = new ContainerVisual(); } return _dummyVisual; } } // NOTE: This class is basically identical to VisualBrush, it should be refactored to // a common place to prevent code duplication (maybe Brush.cs?) void ICyclicBrush.FireOnChanged() { // Simple loop detection to avoid stack overflow in cyclic VisualBrush // scenarios. This fix is only aimed at mitigating a very common // VisualBrush scenario. bool canEnter = Enter(); if (canEnter) { try { FireChanged(); // Register brush's visual tree for Render(). RegisterForAsyncRenderForCyclicBrush(); } finally { Exit(); } } } /// <summary> /// Calling this will make sure that the render request /// is registered with the MediaContext. /// </summary> private void RegisterForAsyncRenderForCyclicBrush() { DUCE.IResource resource = this as DUCE.IResource; if (resource != null) { if ((Dispatcher != null) && !_isAsyncRenderRegistered) { MediaContext mediaContext = MediaContext.From(Dispatcher); // // Only register for a deferred render if this visual brush // is actually on the channel. // if (!resource.GetHandle(mediaContext.Channel).IsNull) { // Add this handler to this event means that the handler will be // called on the next UIThread render for this Dispatcher. ICyclicBrush cyclicBrush = this as ICyclicBrush; mediaContext.ResourcesUpdated += new MediaContext.ResourcesUpdatedHandler(cyclicBrush.RenderForCyclicBrush); _isAsyncRenderRegistered = true; } } } } void ICyclicBrush.RenderForCyclicBrush(DUCE.Channel channel, bool skipChannelCheck) { Visual vVisual = InternalTarget; // The Visual may have been registered for an asynchronous render, but may have been // disconnected from the VisualBrush since then. If so, don't bother to render here, if // the Visual is visible it will be rendered elsewhere. if (vVisual != null && vVisual.CheckFlagsAnd(VisualFlags.NodeIsCyclicBrushRoot)) { // ------------------------------------------------------------------------------------ // 1) Prepare the visual for rendering. // // Updates bounding boxes. // vVisual.Precompute(); // ------------------------------------------------------------------------------------ // 2) Prepare the render context. // RenderContext rc = new RenderContext(); rc.Initialize(channel, DUCE.ResourceHandle.Null); // ------------------------------------------------------------------------------------ // 3) Compile the scene. if (channel.IsConnected) { vVisual.Render(rc, 0); } else { // We can issue the release here instead of putting it in queue // since we are already in Render walk. ((DUCE.IResource)vVisual).ReleaseOnChannel(channel); } } _isAsyncRenderRegistered = false; } // Implement functions used to addref and release resources in codegen that need // to be specialized for Visual which doesn't implement DUCE.IResource internal void AddRefResource(Visual visual, DUCE.Channel channel) { if (visual != null) { visual.AddRefOnChannelForCyclicBrush(this, channel); } } internal void ReleaseResource(Visual visual, DUCE.Channel channel) { if (visual != null) { visual.ReleaseOnChannelForCyclicBrush(this, channel); } } /// <summary> /// Implementation of <see cref="System.Windows.DependencyObject.OnPropertyChanged">DependencyObject.OnPropertyInvalidated</see>. /// If the property is the Visual or the AutoLayoutContent property, we re-layout the Visual if /// possible. /// </summary> protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (e.IsAValueChange || e.IsASubPropertyChange) { if ((e.Property == TargetProperty) || (e.Property == AutoLayoutContentProperty)) { // Should we wrap the visual in a dummy visual node for rendering? if (e.Property == TargetProperty && e.IsAValueChange) { if (AutoWrapTarget) { Debug.Assert(InternalTarget == AutoWrapVisual, "InternalTarget should point to our dummy visual AutoWrapVisual when AutoWrapTarget is true."); // Change the value being wrapped by AutoWrapVisual. AutoWrapVisual.Children.Remove((Visual)e.OldValue); AutoWrapVisual.Children.Add((Visual)e.NewValue); } else { // Target just passes through to InternalTarget. InternalTarget = Target; } } // Should we initiate a layout on this Visual? // Yes, if AutoLayoutContent is true and if the Visual is a UIElement not already in // another tree (i.e. the parent is null) or its not the hwnd root. if (AutoLayoutContent) { Debug.Assert(!_pendingLayout); UIElement element = Target as UIElement; if ((element != null) && ((VisualTreeHelper.GetParent(element) == null && !(element.IsRootElement)) // element is not connected to visual tree, OR || (VisualTreeHelper.GetParent(element) is Visual3D) // element is a 2D child of a 3D object, OR || (VisualTreeHelper.GetParent(element) == InternalTarget))) // element is only connected to visual tree via our wrapper Visual { // // We need 2 ways of initiating layout on the VisualBrush root. // 1. We add a handler such that when the layout is done for the // main tree and LayoutUpdated is fired, then we do layout for the // VisualBrush tree. // However, this can fail in the case where the main tree is composed // of just Visuals and never does layout nor fires LayoutUpdated. So // we also need the following approach. // 2. We do a BeginInvoke to start layout on the Visual. This approach // alone, also falls short in the scenario where if we are already in // MediaContext.DoWork() then we will do layout (for main tree), then look // at Loaded callbacks, then render, and then finally the Dispather will // fire us for layout. So during loaded callbacks we would not have done // layout on the VisualBrush tree. // // Depending upon which of the two layout passes comes first, we cancel // the other layout pass. // element.LayoutUpdated += OnLayoutUpdated; _DispatcherLayoutResult = Dispatcher.BeginInvoke( DispatcherPriority.Normal, new DispatcherOperationCallback(LayoutCallback), element); _pendingLayout = true; } } } else if (e.Property == AutoWrapTargetProperty) { // If our AutoWrap behavior changed, wrap/unwrap the target here. if (AutoWrapTarget) { InternalTarget = AutoWrapVisual; AutoWrapVisual.Children.Add(Target); } else { AutoWrapVisual.Children.Remove(Target); InternalTarget = Target; } } } } /// <summary> /// We initiate the layout on the tree rooted at the Visual to which BitmapCacheBrush points. /// </summary> private void DoLayout(UIElement element) { Debug.Assert(element != null); DependencyObject parent = VisualTreeHelper.GetParent(element); if (!(element.IsRootElement) && (parent == null || parent is Visual3D || parent == InternalTarget)) { // // PropagateResumeLayout sets the LayoutSuspended flag to false if it were true. // UIElement.PropagateResumeLayout(null, element); element.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); element.Arrange(new Rect(element.DesiredSize)); } } /// <summary> /// LayoutUpdate event handler. /// </summary> private void OnLayoutUpdated(object sender, EventArgs args) { Debug.Assert(_pendingLayout); // Target has to be a UIElement since the handler was added to it. UIElement element = (UIElement)Target; Debug.Assert(element != null); // Unregister for the event element.LayoutUpdated -= OnLayoutUpdated; _pendingLayout = false; // // Since we are in this function that means that layoutUpdated fired before // Dispatcher.BeginInvoke fired. So we can abort the DispatcherOperation as // we will do the layout here. // Debug.Assert(_DispatcherLayoutResult != null); Debug.Assert(_DispatcherLayoutResult.Status == DispatcherOperationStatus.Pending); bool abortStatus = _DispatcherLayoutResult.Abort(); Debug.Assert(abortStatus); DoLayout(element); } /// <summary> /// DispatcherOperation callback to initiate layout. /// </summary> /// <param name="arg">The Visual root</param> private object LayoutCallback(object arg) { Debug.Assert(_pendingLayout); UIElement element = arg as UIElement; Debug.Assert(element != null); // // Since we are in this function that means that Dispatcher.BeginInvoke fired // before LayoutUpdated fired. So we can remove the LayoutUpdated handler as // we will do the layout here. // element.LayoutUpdated -= OnLayoutUpdated; _pendingLayout = false; DoLayout(element); return null; } /// <summary> /// Enter is used for simple cycle detection in BitmapCacheBrush. If the method returns false /// the brush has already been entered and cannot be entered again. Matching invocation of Exit /// must be skipped if Enter returns false. /// </summary> internal bool Enter() { if (_reentrancyFlag) { return false; } else { _reentrancyFlag = true; return true; } } /// <summary> /// Exits the BitmapCacheBrush. For more details see Enter method. /// </summary> internal void Exit() { Debug.Assert(_reentrancyFlag); // Exit must be matched with Enter. See Enter comments. _reentrancyFlag = false; } private static object CoerceOpacity(DependencyObject d, object value) { if ((double)value != (double)OpacityProperty.GetDefaultValue(typeof(BitmapCacheBrush))) { throw new InvalidOperationException(SR.Get(SRID.BitmapCacheBrush_OpacityChanged)); } return 1.0; } private static object CoerceTransform(DependencyObject d, object value) { if ((Transform)value != (Transform)TransformProperty.GetDefaultValue(typeof(BitmapCacheBrush))) { throw new InvalidOperationException(SR.Get(SRID.BitmapCacheBrush_TransformChanged)); } return null; } private static object CoerceRelativeTransform(DependencyObject d, object value) { if ((Transform)value != (Transform)RelativeTransformProperty.GetDefaultValue(typeof(BitmapCacheBrush))) { throw new InvalidOperationException(SR.Get(SRID.BitmapCacheBrush_RelativeTransformChanged)); } return null; } private static void StaticInitialize(Type typeofThis) { OpacityProperty.OverrideMetadata(typeofThis, new IndependentlyAnimatedPropertyMetadata(1.0, /* PropertyChangedHandle */ null, CoerceOpacity)); TransformProperty.OverrideMetadata(typeofThis, new UIPropertyMetadata(null, /* PropertyChangedHandle */ null, CoerceTransform)); RelativeTransformProperty.OverrideMetadata(typeofThis, new UIPropertyMetadata(null, /* PropertyChangedHandle */ null, CoerceRelativeTransform)); } private ContainerVisual _dummyVisual; private DispatcherOperation _DispatcherLayoutResult; private bool _pendingLayout; private bool _reentrancyFlag; private bool _isAsyncRenderRegistered = false; } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService { private const double DefaultZoomLevel = 0.75; private readonly ITextViewRoleSet _previewRoleSet; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IDifferenceBufferFactoryService _differenceBufferService; private readonly IWpfDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] public PreviewFactoryService( ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, IWpfDifferenceViewerFactoryService differenceViewerService) { _textBufferFactoryService = textBufferFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _differenceSelectorService = differenceSelectorService; _differenceBufferService = differenceBufferService; _differenceViewerService = differenceViewerService; _previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken) { return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List<SolutionPreviewItem>(); SolutionChangeSummary changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; foreach (var documentId in projectChanges.GetChangedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, (c) => CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, (c) => CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingReferenceTo, metadataReference.Display, oldProject.Name)))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingReferenceFrom, metadataReference.Display, oldProject.Name)))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingReferenceTo, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingReferenceFrom, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingAnalyzerReferenceTo, analyzer.Display, oldProject.Name)))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingAnalyzerReferenceFrom, analyzer.Display, oldProject.Name)))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingProject, project.Name)))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingProject, project.Name)))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(pc => pc.OldProject.AllProjectReferences != pc.NewProject.AllProjectReferences)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.ChangingProjectReferencesFor, projectChanges.OldProject.Name)))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return new SolutionPreviewResult(previewItems, changeSummary); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.AddingToWithContent, document.Name, document.Project.Name); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkspace.OpenAdditionalDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.RemovingFromWithContent, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocument = document.Project .RemoveDocument(document.Id) .AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocumentId = DocumentId.CreateNewId(document.Project.Id); var leftSolution = document.Project.Solution .RemoveAdditionalDocument(document.Id) .AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText); var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. // We also need to show the spans that are in conflict. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); var description = default(string); var allSpans = default(NormalizedSpanCollection); if (newDocument.SupportsSyntaxTree) { var newRoot = newDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList(); var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind)) .Select(a => ConflictAnnotation.GetDescription(a)) .Distinct(); var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind); var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList(); var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind)) .Select(a => WarningAnnotation.GetDescription(a)) .Distinct(); AttachConflictAndWarningAnnotationToBuffer(newBuffer, conflictSpans, warningSpans); description = conflictSpans.Count == 0 && warningSpans.Count == 0 ? null : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions)); allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans)); } else { allSpans = new NormalizedSpanCollection(changedSpans); } var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken); if (!originalLineSpans.Any()) { // This means that we have no differences (likely because of conflicts). // In such cases, use the same spans for the left (old) buffer as the right (new) buffer. originalLineSpans = changedLineSpans; } // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocument = oldDocument.Project .RemoveDocument(oldDocument.Id) .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); var rightWorkspace = new PreviewWorkspace( oldDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkspace, zoomLevel, cancellationToken); } public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); string description = null; var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken); // TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above? // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id); var leftSolution = oldDocument.Project.Solution .RemoveAdditionalDocument(oldDocument.Id) .AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); var rightWorkSpace = new PreviewWorkspace( oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkSpace.OpenAdditionalDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken); } private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description, List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!(originalSpans.Any() && changedSpans.Any())) { // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw. // So if either is empty (signalling that there are no changes to preview in the document), then we bail out. // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed, // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at // this point, the preview that we return will never be displayed to the user. So returning null here is harmless. return SpecializedTasks.Default<object>(); } var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, oldBuffer.CurrentSnapshot, "...", description, originalSpans.ToArray()); var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, newBuffer.CurrentSnapshot, "...", description, changedSpans.ToArray()); return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private static void AttachConflictAndWarningAnnotationToBuffer(ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans) { // Attach the spans to the buffer. newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans)); } private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // is it okay to create buffer from threads other than UI thread? var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var contentType = _textBufferFactoryService.TextContentType; return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private async Task<object> CreateNewDifferenceViewerAsync(PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // leftWorkspace can be null if the change is adding a document. // rightWorkspace can be null if the change is removing a document. // However both leftWorkspace and rightWorkspace can't be null at the same time. Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null)); var diffBuffer = _differenceBufferService.CreateDifferenceBuffer( originalBuffer, changedBuffer, new StringDifferenceOptions(), disableEditing: true); var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet); diffViewer.Closed += (s, e) => { if (leftWorkspace != null) { leftWorkspace.Dispose(); leftWorkspace = null; } if (rightWorkspace != null) { rightWorkspace.Dispose(); rightWorkspace = null; } }; const string DiffOverviewMarginName = "deltadifferenceViewerOverview"; if (leftWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.RightViewOnly; diffViewer.RightView.ZoomLevel *= zoomLevel; diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else if (rightWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly; diffViewer.LeftView.ZoomLevel *= zoomLevel; diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else { diffViewer.ViewMode = DifferenceViewMode.Inline; diffViewer.InlineView.ZoomLevel *= zoomLevel; diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } // Disable focus / tab stop for the diff viewer. diffViewer.RightView.VisualElement.Focusable = false; diffViewer.LeftView.VisualElement.Focusable = false; diffViewer.InlineView.VisualElement.Focusable = false; // This code path must be invoked on UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync().ConfigureAwait(true); if (leftWorkspace != null) { leftWorkspace.EnableDiagnostic(); } if (rightWorkspace != null) { rightWorkspace.EnableDiagnostic(); } return diffViewer; } private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new List<LineSpan>(); foreach (var span in allSpans) { cancellationToken.ThrowIfCancellationRequested(); var lineSpan = GetLineSpan(textSnapshot, span); MergeLineSpans(result, lineSpan); } return result; } // Find the lines that surround the span of the difference. Try to expand the span to // include both the previous and next lines so that we can show more context to the // user. private LineSpan GetLineSpan( ITextSnapshot snapshot, Span span) { var startLine = snapshot.GetLineNumberFromPosition(span.Start); var endLine = snapshot.GetLineNumberFromPosition(span.End); if (startLine > 0) { startLine--; } if (endLine < snapshot.LineCount) { endLine++; } return LineSpan.FromBounds(startLine, endLine); } // Adds a line span to the spans we've been collecting. If the line span overlaps or // abuts a previous span then the two are merged. private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan) { if (lineSpans.Count > 0) { var lastLineSpan = lineSpans.Last(); // We merge them if there's no more than one line between the two. Otherwise // we'd show "..." between two spans where we could just show the actual code. if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1)) { nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End); lineSpans.RemoveAt(lineSpans.Count - 1); } } lineSpans.Add(nextLineSpan); } private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Get the text that's actually in the editor. var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Defer to the editor to figure out what changes the client made. var diffService = _differenceSelectorService.GetTextDifferencingService( oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions() { DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line, }); } private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } } }
//--------------------------------------------------------------------------- // // File: HtmlXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Html - Xaml conversion // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; namespace Gherkin.Model.HtmlConverter { // DependencyProperty // TextElement internal static class HtmlCssParser { // ................................................................. // // Processing CSS Attributes // // ................................................................. internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext) { string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext); string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style"); // Combine styles from stylesheet and from inline attribute. // The order is important - the latter styles will override the former. string style = styleFromStylesheet != null ? styleFromStylesheet : null; if (styleInline != null) { style = style == null ? styleInline : (style + ";" + styleInline); } // Apply local style to current formatting properties if (style != null) { string[] styleValues = style.Split(';'); for (int i = 0; i < styleValues.Length; i++) { string[] styleNameValue; styleNameValue = styleValues[i].Split(':'); if (styleNameValue.Length == 2) { string styleName = styleNameValue[0].Trim().ToLower(); string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(); int nextIndex = 0; switch (styleName) { case "font": ParseCssFont(styleValue, localProperties); break; case "font-family": ParseCssFontFamily(styleValue, ref nextIndex, localProperties); break; case "font-size": ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); break; case "font-style": ParseCssFontStyle(styleValue, ref nextIndex, localProperties); break; case "font-weight": ParseCssFontWeight(styleValue, ref nextIndex, localProperties); break; case "font-variant": ParseCssFontVariant(styleValue, ref nextIndex, localProperties); break; case "line-height": ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); break; case "word-spacing": // Implement word-spacing conversion break; case "letter-spacing": // Implement letter-spacing conversion break; case "color": ParseCssColor(styleValue, ref nextIndex, localProperties, "color"); break; case "text-decoration": ParseCssTextDecoration(styleValue, ref nextIndex, localProperties); break; case "text-transform": ParseCssTextTransform(styleValue, ref nextIndex, localProperties); break; case "background-color": ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color"); break; case "background": // TODO: need to parse composite background property ParseCssBackground(styleValue, ref nextIndex, localProperties); break; case "text-align": ParseCssTextAlign(styleValue, ref nextIndex, localProperties); break; case "vertical-align": ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties); break; case "text-indent": ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false); break; case "width": case "height": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "margin": // top/right/bottom/left ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "margin-top": case "margin-right": case "margin-bottom": case "margin-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "padding": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "padding-top": case "padding-right": case "padding-bottom": case "padding-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "border": ParseCssBorder(styleValue, ref nextIndex, localProperties); break; case "border-style": case "border-width": case "border-color": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "border-top": case "border-right": case "border-left": case "border-bottom": // Parse css border style break; // NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right) // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-top-style": case "border-right-style": case "border-left-style": case "border-bottom-style": case "border-top-color": case "border-right-color": case "border-left-color": case "border-bottom-color": case "border-top-width": case "border-right-width": case "border-left-width": case "border-bottom-width": // Parse css border style break; case "display": // Implement display style conversion break; case "float": ParseCssFloat(styleValue, ref nextIndex, localProperties); break; case "clear": ParseCssClear(styleValue, ref nextIndex, localProperties); break; default: break; } } } } } // ................................................................. // // Parsing CSS - Lexical Helpers // // ................................................................. // Skips whitespaces in style values private static void ParseWhiteSpace(string styleValue, ref int nextIndex) { while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex])) { nextIndex++; } } // Checks if the following character matches to a given word and advances nextIndex // by the word's length in case of success. // Otherwise leaves nextIndex in place (except for possible whitespaces). // Returns true or false depending on success or failure of matching. private static bool ParseWord(string word, string styleValue, ref int nextIndex) { ParseWhiteSpace(styleValue, ref nextIndex); for (int i = 0; i < word.Length; i++) { if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i])) { return false; } } if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length])) { return false; } nextIndex += word.Length; return true; } // CHecks whether the following character sequence matches to one of the given words, // and advances the nextIndex to matched word length. // Returns null in case if there is no match or the word matched. private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex) { for (int i = 0; i < words.Length; i++) { if (ParseWord(words[i], styleValue, ref nextIndex)) { return words[i]; } } return null; } private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName) { string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex); if (attributeValue != null) { localProperties[attributeName] = attributeValue; } } private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative) { ParseWhiteSpace(styleValue, ref nextIndex); int startIndex = nextIndex; // Parse optional munis sign if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-') { nextIndex++; } if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex])) { while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.')) { nextIndex++; } string number = styleValue.Substring(startIndex, nextIndex - startIndex); string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex); if (unit == null) { unit = "px"; // Assuming pixels by default } if (mustBeNonNegative && styleValue[startIndex] == '-') { return "0"; } else { return number + unit; } } return null; } private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative) { string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative); if (length != null) { localValues[propertyName] = length; } } private static readonly string[] _colors = new string[] { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen", }; private static readonly string[] _systemColors = new string[] { "activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext", }; private static string ParseCssColor(string styleValue, ref int nextIndex) { // Implement color parsing // rgb(100%,53.5%,10%) // rgb(255,91,26) // #FF5B1A // black | silver | gray | ... | aqua // transparent - for background-color ParseWhiteSpace(styleValue, ref nextIndex); string color = null; if (nextIndex < styleValue.Length) { int startIndex = nextIndex; char character = styleValue[nextIndex]; if (character == '#') { nextIndex++; while (nextIndex < styleValue.Length) { character = Char.ToUpper(styleValue[nextIndex]); if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F')) { break; } nextIndex++; } if (nextIndex > startIndex + 1) { color = styleValue.Substring(startIndex, nextIndex - startIndex); } } else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg") { // Implement real rgb() color parsing while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')') { nextIndex++; } if (nextIndex < styleValue.Length) { nextIndex++; // to skip ')' } color = "gray"; // return bogus color } else if (Char.IsLetter(character)) { color = ParseWordEnumeration(_colors, styleValue, ref nextIndex); if (color == null) { color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex); if (color != null) { // Implement smarter system color converions into real colors color = "black"; } } } } return color; } private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName) { string color = ParseCssColor(styleValue, ref nextIndex); if (color != null) { localValues[propertyName] = color; } } // ................................................................. // // Pasring CSS font Property // // ................................................................. // CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size. // An aggregated "font" property lets you specify in one action all the five in combination // with additional line-height property. // // font-family: [<family-name>,]* [<family-name> | <generic-family>] // generic-family: serif | sans-serif | monospace | cursive | fantasy // The list of families sets priorities to choose fonts; // Quotes not allowed around generic-family names // font-style: normal | italic | oblique // font-variant: normal | small-caps // font-weight: normal | bold | bolder | lighter | 100 ... 900 | // Default is "normal", normal==400 // font-size: <absolute-size> | <relative-size> | <length> | <percentage> // absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large // relative-size: larger | smaller // length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches> // Default: medium // font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family> private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" }; private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" }; private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" }; private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" }; private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" }; private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" }; // Parses CSS string fontStyle representing a value for css font attribute private static void ParseCssFont(string styleValue, Hashtable localProperties) { int nextIndex = 0; ParseCssFontStyle(styleValue, ref nextIndex, localProperties); ParseCssFontVariant(styleValue, ref nextIndex, localProperties); ParseCssFontWeight(styleValue, ref nextIndex, localProperties); ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/') { nextIndex++; ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); } ParseCssFontFamily(styleValue, ref nextIndex, localProperties); } private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style"); } private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant"); } private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight"); } private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties) { string fontFamilyList = null; while (nextIndex < styleValue.Length) { // Try generic-family string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex); if (fontFamily == null) { // Try quoted font family name if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\'')) { char quote = styleValue[nextIndex]; nextIndex++; int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote) { nextIndex++; } fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"'; } if (fontFamily == null) { // Try unquoted font family name int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';') { nextIndex++; } if (nextIndex > startIndex) { fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim(); if (fontFamily.Length == 0) { fontFamily = null; } } } } ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',') { nextIndex++; } if (fontFamily != null) { // css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names // fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily; if (fontFamilyList == null && fontFamily.Length > 0) { if (fontFamily[0] == '"' || fontFamily[0] == '\'') { // Unquote the font family name fontFamily = fontFamily.Substring(1, fontFamily.Length - 2); } else { // Convert generic css family name } fontFamilyList = fontFamily; } } else { break; } } if (fontFamilyList != null) { localProperties["font-family"] = fontFamilyList; } } // ................................................................. // // Pasring CSS list-style Property // // ................................................................. // list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ] private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" }; private static readonly string[] _listStylePositions = new string[] { "inside", "outside" }; private static void ParseCssListStyle(string styleValue, Hashtable localProperties) { int nextIndex = 0; while (nextIndex < styleValue.Length) { string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex); if (listStyleType != null) { localProperties["list-style-type"] = listStyleType; } else { string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex); if (listStylePosition != null) { localProperties["list-style-position"] = listStylePosition; } else { string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex); if (listStyleImage != null) { localProperties["list-style-image"] = listStyleImage; } else { // TODO: Process unrecognized list style value break; } } } } } private static string ParseCssListStyleType(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex); } private static string ParseCssListStylePosition(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex); } private static string ParseCssListStyleImage(string styleValue, ref int nextIndex) { // TODO: Implement URL parsing for images return null; } // ................................................................. // // Pasring CSS text-decorations Property // // ................................................................. private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" }; private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties) { // Set default text-decorations:none; for (int i = 1; i < _textDecorations.Length; i++) { localProperties["text-decoration-" + _textDecorations[i]] = "false"; } // Parse list of decorations values while (nextIndex < styleValue.Length) { string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex); if (decoration == null || decoration == "none") { break; } localProperties["text-decoration-" + decoration] = "true"; } } // ................................................................. // // Pasring CSS text-transform Property // // ................................................................. private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" }; private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform"); } // ................................................................. // // Pasring CSS text-align Property // // ................................................................. private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" }; private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align"); } // ................................................................. // // Pasring CSS vertical-align Property // // ................................................................. private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" }; private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { // Parse percentage value for vertical-align style ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align"); } // ................................................................. // // Pasring CSS float Property // // ................................................................. private static readonly string[] _floats = new string[] { "left", "right", "none" }; private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float"); } // ................................................................. // // Pasring CSS clear Property // // ................................................................. private static readonly string[] _clears = new string[] { "none", "left", "right", "both" }; private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear"); } // ................................................................. // // Pasring CSS margin and padding Properties // // ................................................................. // Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName) { // CSS Spec: // If only one value is set, then the value applies to all four sides; // If two or three values are set, then missinng value(s) are taken fromm the opposite side(s). // The order they are applied is: top/right/bottom/left Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color"); string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-top"] = value; localProperties[propertyName + "-bottom"] = value; localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-bottom"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-left"] = value; } } } return true; } return false; } // ................................................................. // // Pasring CSS border Properties // // ................................................................. // border: [ <border-width> || <border-style> || <border-color> ] private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties) { while ( ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color")) { } } // ................................................................. // // Pasring CSS border-style Propertie // // ................................................................. private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" }; private static string ParseCssBorderStyle(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex); } // ................................................................. // // What are these definitions doing here: // // ................................................................. private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" }; // ................................................................. // // Pasring CSS Background Properties // // ................................................................. private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues) { // Implement parsing background attribute } } internal class CssStylesheet { // Constructor public CssStylesheet(XmlElement htmlElement) { if (htmlElement != null) { this.DiscoverStyleDefinitions(htmlElement); } } // Recursively traverses an html tree, discovers STYLE elements and creates a style definition table // for further cascading style application public void DiscoverStyleDefinitions(XmlElement htmlElement) { if (htmlElement.LocalName.ToLower() == "link") { return; // Add LINK elements processing for included stylesheets // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet> } if (htmlElement.LocalName.ToLower() != "style") { // This is not a STYLE element. Recurse into it for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { this.DiscoverStyleDefinitions((XmlElement)htmlChildNode); } } return; } // Add style definitions from this style. // Collect all text from this style definition StringBuilder stylesheetBuffer = new StringBuilder(); for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlText || htmlChildNode is XmlComment) { stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value)); } } // CssStylesheet has the following syntactical structure: // @import declaration; // selector { definition } // where "selector" is one of: ".classname", "tagname" // It can contain comments in the following form: /*...*/ int nextCharacterIndex = 0; while (nextCharacterIndex < stylesheetBuffer.Length) { // Extract selector int selectorStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{') { // Skip declaration directive starting from @ if (stylesheetBuffer[nextCharacterIndex] == '@') { while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';') { nextCharacterIndex++; } selectorStart = nextCharacterIndex + 1; } nextCharacterIndex++; } if (nextCharacterIndex < stylesheetBuffer.Length) { // Extract definition int definitionStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}') { nextCharacterIndex++; } // Define a style if (nextCharacterIndex - definitionStart > 2) { this.AddStyleDefinition( stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart), stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2)); } // Skip closing brace if (nextCharacterIndex < stylesheetBuffer.Length) { Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}'); nextCharacterIndex++; } } } } // Returns a string with all c-style comments replaced by spaces private string RemoveComments(string text) { int commentStart = text.IndexOf("/*"); if (commentStart < 0) { return text; } int commentEnd = text.IndexOf("*/", commentStart + 2); if (commentEnd < 0) { return text.Substring(0, commentStart); } return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2)); } public void AddStyleDefinition(string selector, string definition) { // Notrmalize parameter values selector = selector.Trim().ToLower(); definition = definition.Trim().ToLower(); if (selector.Length == 0 || definition.Length == 0) { return; } if (_styleDefinitions == null) { _styleDefinitions = new List<StyleDefinition>(); } string[] simpleSelectors = selector.Split(','); for (int i = 0; i < simpleSelectors.Length; i++) { string simpleSelector = simpleSelectors[i].Trim(); if (simpleSelector.Length > 0) { _styleDefinitions.Add(new StyleDefinition(simpleSelector, definition)); } } } public string GetStyle(string elementName, List<XmlElement> sourceContext) { Debug.Assert(sourceContext.Count > 0); Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName); // Add id processing for style selectors if (_styleDefinitions != null) { for (int i = _styleDefinitions.Count - 1; i >= 0; i--) { string selector = _styleDefinitions[i].Selector; string[] selectorLevels = selector.Split(' '); int indexInSelector = selectorLevels.Length - 1; int indexInContext = sourceContext.Count - 1; string selectorLevel = selectorLevels[indexInSelector].Trim(); if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1])) { return _styleDefinitions[i].Definition; } } } return null; } private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement) { if (selectorLevel.Length == 0) { return false; } int indexOfDot = selectorLevel.IndexOf('.'); int indexOfPound = selectorLevel.IndexOf('#'); string selectorClass = null; string selectorId = null; string selectorTag = null; if (indexOfDot >= 0) { if (indexOfDot > 0) { selectorTag = selectorLevel.Substring(0, indexOfDot); } selectorClass = selectorLevel.Substring(indexOfDot + 1); } else if (indexOfPound >= 0) { if (indexOfPound > 0) { selectorTag = selectorLevel.Substring(0, indexOfPound); } selectorId = selectorLevel.Substring(indexOfPound + 1); } else { selectorTag = selectorLevel; } if (selectorTag != null && selectorTag != xmlElement.LocalName) { return false; } if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId) { return false; } if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass) { return false; } return true; } private class StyleDefinition { public StyleDefinition(string selector, string definition) { this.Selector = selector; this.Definition = definition; } public string Selector; public string Definition; } private List<StyleDefinition> _styleDefinitions; } }
//------------------------------------------------------------------------------ // <copyright file="SqlPipe.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="true" primary="false">daltodov</owner> //------------------------------------------------------------------------------ namespace Microsoft.SqlServer.Server { using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Sql; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; // SqlPipe // Abstraction of TDS data/message channel exposed to user. public sealed class SqlPipe { SmiContext _smiContext; SmiRecordBuffer _recordBufferSent; // Last recordBuffer sent to pipe (for push model SendEnd). SqlMetaData[] _metaDataSent; // Metadata of last resultset started (for push model). Overloaded to indicate if push started or not (non-null/null) SmiEventSink_Default _eventSink; // Eventsink to use when calling SmiContext entrypoints bool _isBusy; // Is this pipe currently handling an operation? bool _hadErrorInResultSet; // true if an exception was thrown from within various bodies; used to control cleanup during SendResultsEnd internal SqlPipe( SmiContext smiContext ) { _smiContext = smiContext; _eventSink = new SmiEventSink_Default(); } // // Public methods // public void ExecuteAndSend( SqlCommand command ) { SetPipeBusy( ); try { EnsureNormalSendValid( "ExecuteAndSend" ); if ( null == command ) { throw ADP.ArgumentNull( "command" ); } SqlConnection connection = command.Connection; // if the command doesn't have a connection set up, try to set one up on it's behalf if ( null == connection ) { using ( SqlConnection newConnection = new SqlConnection( "Context Connection=true" ) ) { newConnection.Open( ); // use try-finally to restore command's connection property to it's original state try { command.Connection = newConnection; command.ExecuteToPipe( _smiContext ); } finally { command.Connection = null; } } } else { // validate connection state if ( ConnectionState.Open != connection.State ) { throw ADP.ClosedConnectionError(); } // validate connection is current scope's connection SqlInternalConnectionSmi internalConnection = connection.InnerConnection as SqlInternalConnectionSmi; if ( null == internalConnection ) { throw SQL.SqlPipeCommandHookedUpToNonContextConnection( ); } command.ExecuteToPipe( _smiContext ); } } finally { ClearPipeBusy( ); } } // Equivalent to TSQL PRINT statement -- sends an info-only message. public void Send( string message ) { ADP.CheckArgumentNull(message, "message"); if ( SmiMetaData.MaxUnicodeCharacters < message.Length ) { throw SQL.SqlPipeMessageTooLong( message.Length ); } SetPipeBusy( ); try { EnsureNormalSendValid( "Send" ); _smiContext.SendMessageToPipe( message, _eventSink ); // Handle any errors that are reported. _eventSink.ProcessMessagesAndThrow(); } catch { _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the Send message!"); } } // Send results from SqlDataReader public void Send( SqlDataReader reader ) { ADP.CheckArgumentNull(reader, "reader"); SetPipeBusy( ); try { EnsureNormalSendValid( "Send" ); do { SmiExtendedMetaData[] columnMetaData = reader.GetInternalSmiMetaData(); if (null != columnMetaData && 0 != columnMetaData.Length) { // SQLBUDT #340528 -- don't send empty results. using ( SmiRecordBuffer recordBuffer = _smiContext.CreateRecordBuffer(columnMetaData, _eventSink) ) { _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. _smiContext.SendResultsStartToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. try { while( reader.Read( ) ) { if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { ValueUtilsSmi.FillCompatibleSettersFromReader(_eventSink, recordBuffer, new List<SmiExtendedMetaData>(columnMetaData), reader); } else { ValueUtilsSmi.FillCompatibleITypedSettersFromReader(_eventSink, recordBuffer, columnMetaData, reader); } _smiContext.SendResultsRowToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. } } finally { _smiContext.SendResultsEndToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. } } } } while ( reader.NextResult( ) ); } catch { _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the Send reader!"); } } public void Send( SqlDataRecord record ) { ADP.CheckArgumentNull(record, "record"); SetPipeBusy( ); try { EnsureNormalSendValid( "Send" ); if (0 != record.FieldCount) { // SQLBUDT #340564 -- don't send empty records. SmiRecordBuffer recordBuffer; if (record.RecordContext == _smiContext) { recordBuffer = record.RecordBuffer; } else { // SendResultsRowToPipe() only takes a RecordBuffer created by an SmiContext SmiExtendedMetaData[] columnMetaData = record.InternalGetSmiMetaData(); recordBuffer = _smiContext.CreateRecordBuffer(columnMetaData, _eventSink); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { ValueUtilsSmi.FillCompatibleSettersFromRecord(_eventSink, recordBuffer, columnMetaData, record, null /* no default values */); } else { ValueUtilsSmi.FillCompatibleITypedSettersFromRecord(_eventSink, recordBuffer, columnMetaData, record); } } _smiContext.SendResultsStartToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. // If SendResultsStartToPipe succeeded, then SendResultsEndToPipe must be called. try { _smiContext.SendResultsRowToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. } finally { _smiContext.SendResultsEndToPipe( recordBuffer, _eventSink ); _eventSink.ProcessMessagesAndThrow(); // Handle any errors that are reported. } } } catch { // VSDD 479525: if exception happens (e.g. SendResultsStartToPipe throw OutOfMemory), _eventSink may not be empty, // which will affect server's behavior if the next call successes (previous exception is still in the eventSink, // will be throwed). So we need to clean _eventSink. _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the Send record!"); } } public void SendResultsStart( SqlDataRecord record ) { ADP.CheckArgumentNull(record, "record"); SetPipeBusy( ); try { EnsureNormalSendValid( "SendResultsStart" ); SmiRecordBuffer recordBuffer = record.RecordBuffer; if (record.RecordContext == _smiContext) { recordBuffer = record.RecordBuffer; } else { recordBuffer = _smiContext.CreateRecordBuffer(record.InternalGetSmiMetaData(), _eventSink); // Only MetaData needed for sending start } _smiContext.SendResultsStartToPipe( recordBuffer, _eventSink ); // Handle any errors that are reported. _eventSink.ProcessMessagesAndThrow(); // remember sent buffer info so it can be used in send row/end. _recordBufferSent = recordBuffer; _metaDataSent = record.InternalGetMetaData(); } catch { _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the SendResultsStart!"); } } public void SendResultsRow( SqlDataRecord record ) { ADP.CheckArgumentNull(record, "record"); SetPipeBusy( ); try { EnsureResultStarted( "SendResultsRow" ); if ( _hadErrorInResultSet ) { throw SQL.SqlPipeErrorRequiresSendEnd(); } // Assume error state unless cleared below _hadErrorInResultSet = true; SmiRecordBuffer recordBuffer; if (record.RecordContext == _smiContext) { recordBuffer = record.RecordBuffer; } else { SmiExtendedMetaData[] columnMetaData = record.InternalGetSmiMetaData(); recordBuffer = _smiContext.CreateRecordBuffer(columnMetaData, _eventSink); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { ValueUtilsSmi.FillCompatibleSettersFromRecord(_eventSink, recordBuffer, columnMetaData, record, null /* no default values */); } else { ValueUtilsSmi.FillCompatibleITypedSettersFromRecord(_eventSink, recordBuffer, columnMetaData, record); } } _smiContext.SendResultsRowToPipe( recordBuffer, _eventSink ); // Handle any errors that are reported. _eventSink.ProcessMessagesAndThrow(); // We successfully traversed the send, clear error state _hadErrorInResultSet = false; } catch { _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the SendResultsRow!"); } } public void SendResultsEnd( ) { SetPipeBusy( ); try { EnsureResultStarted( "SendResultsEnd" ); _smiContext.SendResultsEndToPipe( _recordBufferSent, _eventSink ); // Once end called down to native code, assume end of resultset _metaDataSent = null; _recordBufferSent = null; _hadErrorInResultSet = false; // Handle any errors that are reported. _eventSink.ProcessMessagesAndThrow(); } catch { _eventSink.CleanMessages(); throw; } finally { ClearPipeBusy( ); Debug.Assert(_eventSink.HasMessages == false, "There should be no messages left in _eventsink at the end of the SendResultsEnd!"); } } // This isn't speced, but it may not be a bad idea to implement... public bool IsSendingResults { get { return null != _metaDataSent; } } internal void OnOutOfScope( ) { _metaDataSent = null; _recordBufferSent = null; _hadErrorInResultSet = false; _isBusy = false; } // Pipe busy status. // Ensures user code cannot call any APIs while a send is in progress. // // Public methods must call this method before sending anything to the unmanaged pipe. // Once busy status is set, it must clear before returning from the calling method // ( i.e. clear should be in a finally block). private void SetPipeBusy( ) { if ( _isBusy ) { throw SQL.SqlPipeIsBusy( ); } _isBusy = true; } // Clear the pipe's busy status. private void ClearPipeBusy( ) { _isBusy = false; } // // State validation // One of the Ensure* validation methods should appear at the top of every public method // // Default validation method // Ensures Pipe is not currently transmitting a push-model resultset private void EnsureNormalSendValid( string methodName ) { if ( IsSendingResults ) { throw SQL.SqlPipeAlreadyHasAnOpenResultSet( methodName ); } } private void EnsureResultStarted( string methodName ) { if ( !IsSendingResults ) { throw SQL.SqlPipeDoesNotHaveAnOpenResultSet( methodName ); } } } }
// 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; namespace System.Xml { internal class Base64Decoder : IncrementalReadDecoder { // // Fields // private byte[] _buffer; private int _startIndex; private int _curIndex; private int _endIndex; private int _bits; private int _bitsFilled; private static readonly string s_charsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static readonly byte[] s_mapBase64 = ConstructMapBase64(); private const int MaxValidChar = (int)'z'; private const byte Invalid = unchecked((byte)-1); // // IncrementalReadDecoder interface // internal override int DecodedCount { get { return _curIndex - _startIndex; } } internal override bool IsFull { get { return _curIndex == _endIndex; } } internal override unsafe int Decode(char[] chars, int startPos, int len) { if (chars == null) { throw new ArgumentNullException(nameof(chars)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (chars.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } int bytesDecoded, charsDecoded; fixed (char* pChars = &chars[startPos]) { fixed (byte* pBytes = &_buffer[_curIndex]) { Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } } _curIndex += bytesDecoded; return charsDecoded; } internal override unsafe int Decode(string str, int startPos, int len) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (str.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } int bytesDecoded, charsDecoded; fixed (char* pChars = str) { fixed (byte* pBytes = &_buffer[_curIndex]) { Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } } _curIndex += bytesDecoded; return charsDecoded; } internal override void Reset() { _bitsFilled = 0; _bits = 0; } internal override void SetNextOutputBuffer(Array buffer, int index, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(index >= 0); Debug.Assert(buffer.Length - index >= count); Debug.Assert((buffer as byte[]) != null); _buffer = (byte[])buffer; _startIndex = index; _curIndex = index; _endIndex = index + count; } // // Private methods // private static byte[] ConstructMapBase64() { byte[] mapBase64 = new byte[MaxValidChar + 1]; for (int i = 0; i < mapBase64.Length; i++) { mapBase64[i] = Invalid; } for (int i = 0; i < s_charsBase64.Length; i++) { mapBase64[(int)s_charsBase64[i]] = (byte)i; } return mapBase64; } private unsafe void Decode(char* pChars, char* pCharsEndPos, byte* pBytes, byte* pBytesEndPos, out int charsDecoded, out int bytesDecoded) { #if DEBUG Debug.Assert(pCharsEndPos - pChars >= 0); Debug.Assert(pBytesEndPos - pBytes >= 0); #endif // walk hex digits pairing them up and shoving the value of each pair into a byte byte* pByte = pBytes; char* pChar = pChars; int b = _bits; int bFilled = _bitsFilled; XmlCharType xmlCharType = XmlCharType.Instance; while (pChar < pCharsEndPos && pByte < pBytesEndPos) { char ch = *pChar; // end? if (ch == '=') { break; } pChar++; // ignore whitespace if (xmlCharType.IsWhiteSpace(ch)) { continue; } int digit; if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid) { throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))); } b = (b << 6) | digit; bFilled += 6; if (bFilled >= 8) { // get top eight valid bits *pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF); bFilled -= 8; if (pByte == pBytesEndPos) { goto Return; } } } if (pChar < pCharsEndPos && *pChar == '=') { bFilled = 0; // ignore padding chars do { pChar++; } while (pChar < pCharsEndPos && *pChar == '='); // ignore whitespace after the padding chars if (pChar < pCharsEndPos) { do { if (!(xmlCharType.IsWhiteSpace(*pChar++))) { throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))); } } while (pChar < pCharsEndPos); } } Return: _bits = b; _bitsFilled = bFilled; bytesDecoded = (int)(pByte - pBytes); charsDecoded = (int)(pChar - pChars); } } }
// 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 class ExpressionTreeRewriter : ExprVisitorBase { public static EXPR Rewrite(EXPR expr, ExprFactory expressionFactory, SymbolLoader symbolLoader) { ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader); rewriter.alwaysRewrite = true; return rewriter.Visit(expr); } protected ExprFactory expressionFactory; protected SymbolLoader symbolLoader; protected EXPRBOUNDLAMBDA currentAnonMeth; protected bool alwaysRewrite; protected ExprFactory GetExprFactory() { return expressionFactory; } protected SymbolLoader GetSymbolLoader() { return symbolLoader; } protected ExpressionTreeRewriter(ExprFactory expressionFactory, SymbolLoader symbolLoader) { this.expressionFactory = expressionFactory; this.symbolLoader = symbolLoader; this.alwaysRewrite = false; } protected override EXPR Dispatch(EXPR expr) { Debug.Assert(expr != null); EXPR result; result = base.Dispatch(expr); if (result == expr) { throw Error.InternalCompilerError(); } return result; } ///////////////////////////////////////////////////////////////////////////////// // Statement types. protected override EXPR VisitASSIGNMENT(EXPRASSIGNMENT assignment) { Debug.Assert(assignment != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); // For assignments, we either have a member assignment or an indexed assignment. //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL()); EXPR lhs; if (assignment.GetLHS().isPROP()) { EXPRPROP prop = assignment.GetLHS().asPROP(); if (prop.GetOptionalArguments() == null) { // Regular property. lhs = Visit(prop); } else { // Indexed assignment. Here we need to find the instance of the object, create the // PropInfo for the thing, and get the array of expressions that make up the index arguments. // // The LHS becomes Expression.Property(instance, indexerInfo, arguments). EXPR instance = Visit(prop.GetMemberGroup().GetOptionalObject()); EXPR propInfo = GetExprFactory().CreatePropertyInfo(prop.pwtSlot.Prop(), prop.pwtSlot.Ats); EXPR arguments = GenerateParamsArray( GenerateArgsList(prop.GetOptionalArguments()), PredefinedType.PT_EXPRESSION); lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments); } } else { lhs = Visit(assignment.GetLHS()); } EXPR rhs = Visit(assignment.GetRHS()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } protected override EXPR VisitMULTIGET(EXPRMULTIGET pExpr) { return Visit(pExpr.GetOptionalMulti().Left); } protected override EXPR VisitMULTI(EXPRMULTI pExpr) { EXPR rhs = Visit(pExpr.Operator); EXPR lhs = Visit(pExpr.Left); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } ///////////////////////////////////////////////////////////////////////////////// // Expression types. protected override EXPR VisitBOUNDLAMBDA(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); EXPRBOUNDLAMBDA prevAnonMeth = currentAnonMeth; currentAnonMeth = anonmeth; MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA); CType delegateType = anonmeth.DelegateType(); TypeArray lambdaTypeParams = GetSymbolLoader().getBSymmgr().AllocParams(1, new CType[] { delegateType }); AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams); EXPR createParameters = CreateWraps(anonmeth); EXPR body = RewriteLambdaBody(anonmeth); EXPR parameters = RewriteLambdaParameters(anonmeth); EXPR args = GetExprFactory().CreateList(body, parameters); CType typeRet = GetSymbolLoader().GetTypeManager().SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPR callLambda = GetExprFactory().CreateCall(0, typeRet, args, pMemGroup, mwi); callLambda.asCALL().PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA; currentAnonMeth = prevAnonMeth; if (createParameters != null) { callLambda = GetExprFactory().CreateSequence(createParameters, callLambda); } EXPR expr = DestroyWraps(anonmeth, callLambda); // If we are already inside an expression tree rewrite and this is an expression tree lambda // then it needs to be quoted. if (currentAnonMeth != null) { expr = GenerateCall(PREDEFMETH.PM_EXPRESSION_QUOTE, expr); } return expr; } protected override EXPR VisitCONSTANT(EXPRCONSTANT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateConstant(expr); } protected override EXPR VisitLOCAL(EXPRLOCAL local) { Debug.Assert(local != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(!local.local.isThis); // this is true for all parameters of an expression lambda if (local.local.wrap != null) { return local.local.wrap; } Debug.Assert(local.local.fUsedInAnonMeth); return GetExprFactory().CreateHoistedLocalInExpression(local); } protected override EXPR VisitTHISPOINTER(EXPRTHISPOINTER expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(expr.local.isThis); return GenerateConstant(expr); } protected override EXPR VisitFIELD(EXPRFIELD expr) { Debug.Assert(expr != null); EXPR pObject; if (expr.GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.GetOptionalObject()); } EXPRFIELDINFO pFieldInfo = GetExprFactory().CreateFieldInfo(expr.fwt.Field(), expr.fwt.GetType()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo); } protected override EXPR VisitUSERDEFINEDCONVERSION(EXPRUSERDEFINEDCONVERSION expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateUserDefinedConversion(expr, expr.Argument); } protected override EXPR VisitCAST(EXPRCAST pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR pArgument = pExpr.GetArgument(); // If we have generated an identity cast or reference cast to a base class // we can omit the cast. if (pArgument.type == pExpr.type || GetSymbolLoader().IsBaseClassOfClass(pArgument.type, pExpr.type) || CConversions.FImpRefConv(GetSymbolLoader(), pArgument.type, pExpr.type)) { return Visit(pArgument); } // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree. if (pExpr.type != null && pExpr.type.isPredefType(PredefinedType.PT_G_EXPRESSION) && pArgument.isBOUNDLAMBDA()) { return Visit(pArgument); } EXPR result = GenerateConversion(pArgument, pExpr.type, pExpr.isChecked()); if ((pExpr.flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter. result.flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } return result; } protected override EXPR VisitCONCAT(EXPRCONCAT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; if (expr.GetFirstArgument().type.isPredefType(PredefinedType.PT_STRING) && expr.GetSecondArgument().type.isPredefType(PredefinedType.PT_STRING)) { pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2; } else { pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2; } EXPR p1 = Visit(expr.GetFirstArgument()); EXPR p2 = Visit(expr.GetSecondArgument()); MethodSymbol method = GetPreDefMethod(pdm); EXPR methodInfo = GetExprFactory().CreateMethodInfo(method, GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING), null); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo); } protected override EXPR VisitBINOP(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); if (expr.GetUserDefinedCallMethod() != null) { return GenerateUserDefinedBinaryOperator(expr); } else { return GenerateBuiltInBinaryOperator(expr); } } protected override EXPR VisitUNARYOP(EXPRUNARYOP pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); if (pExpr.UserDefinedCallMethod != null) { return GenerateUserDefinedUnaryOperator(pExpr); } else { return GenerateBuiltInUnaryOperator(pExpr); } } protected override EXPR VisitARRAYINDEX(EXPRARRAYINDEX pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR arr = Visit(pExpr.GetArray()); EXPR args = GenerateIndexList(pExpr.GetIndex()); if (args.isLIST()) { EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args); } protected override EXPR VisitARRAYLENGTH(EXPRARRAYLENGTH pExpr) { return GenerateBuiltInUnaryOperator(PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, pExpr.GetArray(), pExpr); } protected override EXPR VisitQUESTIONMARK(EXPRQUESTIONMARK pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR p1 = Visit(pExpr.GetTestExpression()); EXPR p2 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalLeftChild()); EXPR p3 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalRightChild()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONDITION, p1, p2, p3); } protected override EXPR VisitCALL(EXPRCALL expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); switch (expr.nubLiftKind) { default: break; case NullableCallLiftKind.NullableIntermediateConversion: case NullableCallLiftKind.NullableConversion: case NullableCallLiftKind.NullableConversionConstructor: return GenerateConversion(expr.GetOptionalArguments(), expr.type, expr.isChecked()); case NullableCallLiftKind.NotLiftedIntermediateConversion: case NullableCallLiftKind.UserDefinedConversion: return GenerateUserDefinedConversion(expr.GetOptionalArguments(), expr.type, expr.mwi); } if (expr.mwi.Meth().IsConstructor()) { return GenerateConstructor(expr); } EXPRMEMGRP memberGroup = expr.GetMemberGroup(); if (memberGroup.isDelegate()) { return GenerateDelegateInvoke(expr); } EXPR pObject; if (expr.mwi.Meth().isStatic || expr.GetMemberGroup().GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = expr.GetMemberGroup().GetOptionalObject(); // If we have, say, an int? which is the object of a call to ToString // then we do NOT want to generate ((object)i).ToString() because that // will convert a null-valued int? to a null object. Rather what we want // to do is box it to a ValueType and call ValueType.ToString. // // To implement this we say that if the object of the call is an implicit boxing cast // then just generate the object, not the cast. If the cast is explicit in the // source code then it will be an EXPLICITCAST and we will visit it normally. // // It might be better to rewrite the expression tree API so that it // can handle in the general case all implicit boxing conversions. Right now it // requires that all arguments to a call that need to be boxed be explicitly boxed. if (pObject != null && pObject.isCAST() && pObject.asCAST().IsBoxingCast()) { pObject = pObject.asCAST().GetArgument(); } pObject = Visit(pObject); } EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.mwi); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL; Debug.Assert(!expr.mwi.Meth().isVirtual || expr.GetMemberGroup().GetOptionalObject() != null); return GenerateCall(pdm, pObject, methodInfo, Params); } protected override EXPR VisitPROP(EXPRPROP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR pObject; if (expr.pwtSlot.Prop().isStatic || expr.GetMemberGroup().GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.GetMemberGroup().GetOptionalObject()); } EXPR propInfo = GetExprFactory().CreatePropertyInfo(expr.pwtSlot.Prop(), expr.pwtSlot.GetType()); if (expr.GetOptionalArguments() != null) { // It is an indexer property. Turn it into a virtual method call. EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo); } protected override EXPR VisitARRINIT(EXPRARRINIT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); // POSSIBLE ERROR: Multi-d should be an error? EXPR pTypeOf = CreateTypeOf(expr.type.AsArrayType().GetElementType()); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params); } protected override EXPR VisitZEROINIT(EXPRZEROINIT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(expr.OptionalArgument == null); if (expr.IsConstructor) { // We have a parameterless "new MyStruct()" which has been realized as a zero init. EXPRTYPEOF pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_TYPE, pTypeOf); } return GenerateConstant(expr); } protected override EXPR VisitTYPEOF(EXPRTYPEOF expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateConstant(expr); } protected virtual EXPR GenerateQuestionMarkOperand(EXPR pExpr) { Debug.Assert(pExpr != null); // We must not optimize away compiler-generated reference casts because // the expression tree API insists that the CType of both sides be identical. if (pExpr.isCAST()) { return GenerateConversion(pExpr.asCAST().GetArgument(), pExpr.type, pExpr.isChecked()); } return Visit(pExpr); } protected virtual EXPR GenerateDelegateInvoke(EXPRCALL expr) { Debug.Assert(expr != null); EXPRMEMGRP memberGroup = expr.GetMemberGroup(); Debug.Assert(memberGroup.isDelegate()); EXPR oldObject = memberGroup.GetOptionalObject(); Debug.Assert(oldObject != null); EXPR pObject = Visit(oldObject); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params); } protected virtual EXPR GenerateBuiltInBinaryOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break; case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break; case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break; case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR; break; case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND; break; case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break; case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break; case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break; case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break; case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break; case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break; case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break; case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break; case ExpressionKind.EK_MUL: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY; break; case ExpressionKind.EK_SUB: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT; break; case ExpressionKind.EK_ADD: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD; break; default: throw Error.InternalCompilerError(); } EXPR origL = expr.GetOptionalLeftChild(); EXPR origR = expr.GetOptionalRightChild(); Debug.Assert(origL != null); Debug.Assert(origR != null); CType typeL = origL.type; CType typeR = origR.type; EXPR newL = Visit(origL); EXPR newR = Visit(origR); bool didEnumConversion = false; CType convertL = null; CType convertR = null; if (typeL.isEnumType()) { // We have already inserted casts if not lifted, so we should never see an enum. Debug.Assert(expr.isLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.underlyingEnumType()); typeL = convertL; didEnumConversion = true; } else if (typeL.IsNullableType() && typeL.StripNubs().isEnumType()) { Debug.Assert(expr.isLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.StripNubs().underlyingEnumType()); typeL = convertL; didEnumConversion = true; } if (typeR.isEnumType()) { Debug.Assert(expr.isLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.underlyingEnumType()); typeR = convertR; didEnumConversion = true; } else if (typeR.IsNullableType() && typeR.StripNubs().isEnumType()) { Debug.Assert(expr.isLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.StripNubs().underlyingEnumType()); typeR = convertR; didEnumConversion = true; } if (typeL.IsNullableType() && typeL.StripNubs() == typeR) { convertR = typeL; } if (typeR.IsNullableType() && typeR.StripNubs() == typeL) { convertL = typeR; } if (convertL != null) { newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL)); } if (convertR != null) { newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR)); } EXPR call = GenerateCall(pdm, newL, newR); if (didEnumConversion && expr.type.StripNubs().isEnumType()) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.type)); } return call; } protected virtual EXPR GenerateBuiltInUnaryOperator(EXPRUNARYOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_UPLUS: return Visit(expr.Child); case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.EK_NEG: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE; break; default: throw Error.InternalCompilerError(); } EXPR origOp = expr.Child; return GenerateBuiltInUnaryOperator(pdm, origOp, expr); } protected virtual EXPR GenerateBuiltInUnaryOperator(PREDEFMETH pdm, EXPR pOriginalOperator, EXPR pOperator) { EXPR op = Visit(pOriginalOperator); if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType()) { Debug.Assert(pOperator.kind == ExpressionKind.EK_BITNOT); // The only built-in unary operator defined on nullable enum. CType underlyingType = pOriginalOperator.type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); op = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, op, CreateTypeOf(nullableType)); } EXPR call = GenerateCall(pdm, op); if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType()) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(pOperator.type)); } return call; } protected virtual EXPR GenerateUserDefinedBinaryOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break; case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break; case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break; case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break; case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break; case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break; case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break; case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break; case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break; case ExpressionKind.EK_STRINGEQ: case ExpressionKind.EK_STRINGNE: case ExpressionKind.EK_DELEGATEEQ: case ExpressionKind.EK_DELEGATENE: case ExpressionKind.EK_EQ: case ExpressionKind.EK_NE: case ExpressionKind.EK_GE: case ExpressionKind.EK_GT: case ExpressionKind.EK_LE: case ExpressionKind.EK_LT: return GenerateUserDefinedComparisonOperator(expr); case ExpressionKind.EK_DELEGATESUB: case ExpressionKind.EK_SUB: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED; break; case ExpressionKind.EK_DELEGATEADD: case ExpressionKind.EK_ADD: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED; break; case ExpressionKind.EK_MUL: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } EXPR p1 = expr.GetOptionalLeftChild(); EXPR p2 = expr.GetOptionalRightChild(); EXPR udcall = expr.GetOptionalUserDefinedCall(); if (udcall != null) { Debug.Assert(udcall.kind == ExpressionKind.EK_CALL || udcall.kind == ExpressionKind.EK_USERLOGOP); if (udcall.kind == ExpressionKind.EK_CALL) { EXPRLIST args = udcall.asCALL().GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement(); p2 = args.GetOptionalNextListNode(); } else { EXPRLIST args = udcall.asUSERLOGOP().OperatorCall.GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement().asWRAP().GetOptionalExpression(); p2 = args.GetOptionalNextListNode(); } } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod()); EXPR call = GenerateCall(pdm, p1, p2, methodInfo); // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate, // not the operand delegate CType. We must cast to the delegate CType. if (expr.kind == ExpressionKind.EK_DELEGATESUB || expr.kind == ExpressionKind.EK_DELEGATEADD) { EXPR pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } return call; } protected virtual EXPR GenerateUserDefinedUnaryOperator(EXPRUNARYOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; EXPR arg = expr.Child; EXPRCALL call = expr.OptionalUserDefinedCall.asCALL(); if (call != null) { // Use the actual argument of the call; it may contain user-defined // conversions or be a bound lambda, and that will not be in the original // argument stashed away in the left child of the operator. arg = call.GetOptionalArguments(); } Debug.Assert(arg != null && arg.kind != ExpressionKind.EK_LIST); switch (expr.kind) { case ExpressionKind.EK_TRUE: case ExpressionKind.EK_FALSE: return Visit(call); case ExpressionKind.EK_UPLUS: pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED; break; case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.EK_DECIMALNEG: case ExpressionKind.EK_NEG: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED; break; case ExpressionKind.EK_INC: case ExpressionKind.EK_DEC: case ExpressionKind.EK_DECIMALINC: case ExpressionKind.EK_DECIMALDEC: pdm = PREDEFMETH.PM_EXPRESSION_CALL; break; default: throw Error.InternalCompilerError(); } EXPR op = Visit(arg); EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod); if (expr.kind == ExpressionKind.EK_INC || expr.kind == ExpressionKind.EK_DEC || expr.kind == ExpressionKind.EK_DECIMALINC || expr.kind == ExpressionKind.EK_DECIMALDEC) { return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION)); } return GenerateCall(pdm, op, methodInfo); } protected virtual EXPR GenerateUserDefinedComparisonOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_DELEGATEEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_DELEGATENE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break; case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } EXPR p1 = expr.GetOptionalLeftChild(); EXPR p2 = expr.GetOptionalRightChild(); if (expr.GetOptionalUserDefinedCall() != null) { EXPRCALL udcall = expr.GetOptionalUserDefinedCall().asCALL(); EXPRLIST args = udcall.GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement(); p2 = args.GetOptionalNextListNode(); } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); EXPR lift = GetExprFactory().CreateBoolConstant(false); // We never lift to null in C#. EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod()); return GenerateCall(pdm, p1, p2, lift, methodInfo); } protected EXPR RewriteLambdaBody(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); Debug.Assert(anonmeth.OptionalBody != null); Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements() != null); // There ought to be no way to get an empty statement block successfully converted into an expression tree. Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements().GetOptionalNextStatement() == null); EXPRBLOCK body = anonmeth.OptionalBody; // The most likely case: if (body.GetOptionalStatements().isRETURN()) { Debug.Assert(body.GetOptionalStatements().asRETURN().GetOptionalObject() != null); return Visit(body.GetOptionalStatements().asRETURN().GetOptionalObject()); } // This can only if it is a void delegate and this is a void expression, such as a call to a void method // or something like Expression<Action<Foo>> e = (Foo f) => f.MyEvent += MyDelegate; throw Error.InternalCompilerError(); } protected EXPR RewriteLambdaParameters(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); // new ParameterExpression[2] {Parameter(typeof(type1), name1), Parameter(typeof(type2), name2)} EXPR paramArrayInitializerArgs = null; EXPR paramArrayInitializerArgsTail = paramArrayInitializerArgs; for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } GetExprFactory().AppendItemToList(local.wrap, ref paramArrayInitializerArgs, ref paramArrayInitializerArgsTail); } return GenerateParamsArray(paramArrayInitializerArgs, PredefinedType.PT_PARAMETEREXPRESSION); } protected virtual EXPR GenerateConversion(EXPR arg, CType CType, bool bChecked) { return GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked()); } protected virtual EXPR GenerateConversionWithSource(EXPR pTarget, CType pType, bool bChecked) { PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; EXPR pTypeOf = CreateTypeOf(pType); return GenerateCall(pdm, pTarget, pTypeOf); } protected virtual EXPR GenerateValueAccessConversion(EXPR pArgument) { Debug.Assert(pArgument != null); CType pStrippedTypeOfArgument = pArgument.type.StripNubs(); EXPR pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr); } protected virtual EXPR GenerateUserDefinedConversion(EXPR arg, CType type, MethWithInst method) { EXPR target = Visit(arg); return GenerateUserDefinedConversion(arg, type, target, method); } protected virtual EXPR GenerateUserDefinedConversion(EXPR arg, CType CType, EXPR target, MethWithInst method) { // The user-defined explicit conversion from enum? to decimal or decimal? requires // that we convert the enum? to its nullable underlying CType. if (isEnumToDecimalConversion(arg.type, CType)) { // Special case: If we have enum? to decimal? then we need to emit // a conversion from enum? to its nullable underlying CType first. // This is unfortunate; we ought to reorganize how conversions are // represented in the EXPR tree so that this is more transparent. // converting an enum to its underlying CType never fails, so no need to check it. CType underlyingType = arg.type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); EXPR typeofNubEnum = CreateTypeOf(nullableType); target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum); } // If the methodinfo does not return the target CType AND this is not a lifted conversion // from one value CType to another, then we need to wrap the whole thing in another conversion, // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S)) CType pMethodReturnType = GetSymbolLoader().GetTypeManager().SubstType(method.Meth().RetType, method.GetType(), method.TypeArgs); bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.type) && IsNullableValueType(CType))); EXPR typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType); EXPR methodInfo = GetExprFactory().CreateMethodInfo(method); PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED; EXPR callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo); if (fDontLiftReturnType) { return callUserDefinedConversion; } PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; EXPR typeofOuter = CreateTypeOf(CType); return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter); } protected virtual EXPR GenerateUserDefinedConversion(EXPRUSERDEFINEDCONVERSION pExpr, EXPR pArgument) { EXPR pCastCall = pExpr.UserDefinedCall; EXPR pCastArgument = pExpr.Argument; EXPR pConversionSource = null; if (!isEnumToDecimalConversion(pArgument.type, pExpr.type) && IsNullableValueAccess(pCastArgument, pArgument)) { // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it. pConversionSource = GenerateValueAccessConversion(pArgument); } else if (pCastCall.isCALL() && pCastCall.asCALL().pConversions != null) { EXPR pUDConversion = pCastCall.asCALL().pConversions; if (pUDConversion.isCALL()) { EXPR pUDConversionArgument = pUDConversion.asCALL().GetOptionalArguments(); if (IsNullableValueAccess(pUDConversionArgument, pArgument)) { pConversionSource = GenerateValueAccessConversion(pArgument); } else { pConversionSource = Visit(pUDConversionArgument); } return GenerateConversionWithSource(pConversionSource, pCastCall.type, pCastCall.asCALL().isChecked()); } else { // This can happen if we have a UD conversion from C to, say, int, // and we have an explicit cast to decimal?. The conversion should // then be bound as two chained user-defined conversions. Debug.Assert(pUDConversion.isUSERDEFINEDCONVERSION()); // Just recurse. return GenerateUserDefinedConversion(pUDConversion.asUSERDEFINEDCONVERSION(), pArgument); } } else { pConversionSource = Visit(pCastArgument); } return GenerateUserDefinedConversion(pCastArgument, pExpr.type, pConversionSource, pExpr.UserDefinedCallMethod); } protected virtual EXPR GenerateParameter(string name, CType CType) { GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING); // force an ensure state EXPRCONSTANT nameString = GetExprFactory().CreateStringConstant(name); EXPRTYPEOF pTypeOf = CreateTypeOf(CType); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString); } protected MethodSymbol GetPreDefMethod(PREDEFMETH pdm) { return GetSymbolLoader().getPredefinedMembers().GetMethod(pdm); } protected EXPRTYPEOF CreateTypeOf(CType CType) { return GetExprFactory().CreateTypeOf(CType); } protected EXPR CreateWraps(EXPRBOUNDLAMBDA anonmeth) { EXPR sequence = null; for (Symbol sym = anonmeth.ArgumentScope().firstChild; sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } Debug.Assert(anonmeth.OptionalBody != null); EXPR create = GenerateParameter(local.name.Text, local.GetType()); local.wrap = GetExprFactory().CreateWrapNoAutoFree(anonmeth.OptionalBody.OptionalScopeSymbol, create); EXPR save = GetExprFactory().CreateSave(local.wrap); if (sequence == null) { sequence = save; } else { sequence = GetExprFactory().CreateSequence(sequence, save); } } return sequence; } protected EXPR DestroyWraps(EXPRBOUNDLAMBDA anonmeth, EXPR sequence) { for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } Debug.Assert(local.wrap != null); Debug.Assert(anonmeth.OptionalBody != null); EXPR freeWrap = GetExprFactory().CreateWrap(anonmeth.OptionalBody.OptionalScopeSymbol, local.wrap); sequence = GetExprFactory().CreateReverseSequence(sequence, freeWrap); } return sequence; } protected virtual EXPR GenerateConstructor(EXPRCALL expr) { Debug.Assert(expr != null); Debug.Assert(expr.mwi.Meth().IsConstructor()); // Realize a call to new DELEGATE(obj, FUNCPTR) as though it actually was // (DELEGATE)CreateDelegate(typeof(DELEGATE), obj, GetMethInfoFromHandle(FUNCPTR)) if (IsDelegateConstructorCall(expr)) { return GenerateDelegateConstructor(expr); } EXPR constructorInfo = GetExprFactory().CreateMethodInfo(expr.mwi); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); if (expr.type.IsAggregateType() && expr.type.AsAggregateType().getAggregate().IsAnonymousType()) { EXPR members = GenerateMembersArray(expr.type.AsAggregateType(), PredefinedType.PT_METHODINFO); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, constructorInfo, Params, members); } else { return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params); } } protected virtual EXPR GenerateDelegateConstructor(EXPRCALL expr) { // In: // // new DELEGATE(obj, &FUNC) // // Out: // // Cast( // Call( // null, // (MethodInfo)GetMethodFromHandle(&CreateDelegate), // new Expression[3]{ // Constant(typeof(DELEGATE)), // transformed-object, // Constant((MethodInfo)GetMethodFromHandle(&FUNC)}), // typeof(DELEGATE)) // Debug.Assert(expr != null); Debug.Assert(expr.mwi.Meth().IsConstructor()); Debug.Assert(expr.type.isDelegateType()); Debug.Assert(expr.GetOptionalArguments() != null); Debug.Assert(expr.GetOptionalArguments().isLIST()); EXPRLIST origArgs = expr.GetOptionalArguments().asLIST(); EXPR target = origArgs.GetOptionalElement(); Debug.Assert(origArgs.GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR); EXPRFUNCPTR funcptr = origArgs.GetOptionalNextListNode().asFUNCPTR(); MethodSymbol createDelegateMethod = GetPreDefMethod(PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT); AggregateType delegateType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_DELEGATE, true); MethWithInst mwi = new MethWithInst(createDelegateMethod, delegateType); EXPR instance = GenerateConstant(GetExprFactory().CreateMethodInfo(funcptr.mwi)); EXPR methinfo = GetExprFactory().CreateMethodInfo(mwi); EXPR param1 = GenerateConstant(CreateTypeOf(expr.type)); EXPR param2 = Visit(target); EXPR paramsList = GetExprFactory().CreateList(param1, param2); EXPR Params = GenerateParamsArray(paramsList, PredefinedType.PT_EXPRESSION); EXPR call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CALL, instance, methinfo, Params); EXPR pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } protected virtual EXPR GenerateArgsList(EXPR oldArgs) { EXPR newArgs = null; EXPR newArgsTail = newArgs; for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext()) { EXPR oldArg = it.Current(); GetExprFactory().AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail); } return newArgs; } protected virtual EXPR GenerateIndexList(EXPR oldIndices) { CType intType = symbolLoader.GetReqPredefType(PredefinedType.PT_INT, true); EXPR newIndices = null; EXPR newIndicesTail = newIndices; for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext()) { EXPR newIndex = it.Current(); if (newIndex.type != intType) { EXPRCLASS exprType = expressionFactory.CreateClass(intType, null, null); newIndex = expressionFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, exprType, newIndex); newIndex.flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } EXPR rewrittenIndex = Visit(newIndex); expressionFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail); } return newIndices; } protected virtual EXPR GenerateConstant(EXPR expr) { EXPRFLAG flags = 0; AggregateType pObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true); if (expr.type.IsNullType()) { EXPRTYPEOF pTypeOf = CreateTypeOf(pObject); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf); } AggregateType stringType = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING, true); if (expr.type != stringType) { flags = EXPRFLAG.EXF_BOX; } EXPRCLASS objectType = GetExprFactory().MakeClass(pObject); EXPRCAST cast = GetExprFactory().CreateCast(flags, objectType, expr); EXPRTYPEOF pTypeOf2 = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2); } protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1) { MethodSymbol method = GetPreDefMethod(pdm); // this should be enforced in an earlier pass and the transform pass should not // be handling this error if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3, EXPR arg4) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3, arg4); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } protected virtual EXPRARRINIT GenerateParamsArray(EXPR args, PredefinedType pt) { int parameterCount = ExpressionIterator.Count(args); AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true); ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1); EXPRCONSTANT paramsArrayArg = GetExprFactory().CreateIntegerConstant(parameterCount); EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, args, paramsArrayArg, null); arrayInit.dimSize = parameterCount; arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory? return arrayInit; } protected virtual EXPRARRINIT GenerateMembersArray(AggregateType anonymousType, PredefinedType pt) { EXPR newArgs = null; EXPR newArgsTail = newArgs; int methodCount = 0; AggregateSymbol aggSym = anonymousType.getAggregate(); for (Symbol member = aggSym.firstChild; member != null; member = member.nextChild) { if (member.IsMethodSymbol()) { MethodSymbol method = member.AsMethodSymbol(); if (method.MethKind() == MethodKindEnum.PropAccessor) { EXPRMETHODINFO methodInfo = GetExprFactory().CreateMethodInfo(method, anonymousType, method.Params); GetExprFactory().AppendItemToList(methodInfo, ref newArgs, ref newArgsTail); methodCount++; } } } AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true); ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1); EXPRCONSTANT paramsArrayArg = GetExprFactory().CreateIntegerConstant(methodCount); EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, newArgs, paramsArrayArg, null); arrayInit.dimSize = methodCount; arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory? return arrayInit; } protected void FixLiftedUserDefinedBinaryOperators(EXPRBINOP expr, ref EXPR pp1, ref EXPR pp2) { // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then // we need to ensure that the unlifted actual arguments are promoted to their nullable CType. Debug.Assert(expr != null); Debug.Assert(pp1 != null); Debug.Assert(pp1 != null); Debug.Assert(pp2 != null); Debug.Assert(pp2 != null); MethodSymbol method = expr.GetUserDefinedCallMethod().Meth(); EXPR orig1 = expr.GetOptionalLeftChild(); EXPR orig2 = expr.GetOptionalRightChild(); Debug.Assert(orig1 != null && orig2 != null); EXPR new1 = pp1; EXPR new2 = pp2; CType fptype1 = method.Params.Item(0); CType fptype2 = method.Params.Item(1); CType aatype1 = orig1.type; CType aatype2 = orig2.type; // Is the operator even a candidate for lifting? if (fptype1.IsNullableType() || fptype2.IsNullableType() || !fptype1.IsAggregateType() || !fptype2.IsAggregateType() || !fptype1.AsAggregateType().getAggregate().IsValueType() || !fptype2.AsAggregateType().getAggregate().IsValueType()) { return; } CType nubfptype1 = GetSymbolLoader().GetTypeManager().GetNullable(fptype1); CType nubfptype2 = GetSymbolLoader().GetTypeManager().GetNullable(fptype2); // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1? if (aatype1.IsNullType() || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2.IsNullType())) { new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1)); } // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2? if (aatype2.IsNullType() || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1.IsNullType())) { new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2)); } pp1 = new1; pp2 = new2; } protected bool IsNullableValueType(CType pType) { if (pType.IsNullableType()) { CType pStrippedType = pType.StripNubs(); return pStrippedType.IsAggregateType() && pStrippedType.AsAggregateType().getAggregate().IsValueType(); } return false; } protected bool IsNullableValueAccess(EXPR pExpr, EXPR pObject) { Debug.Assert(pExpr != null); return pExpr.isPROP() && (pExpr.asPROP().GetMemberGroup().GetOptionalObject() == pObject) && pObject.type.IsNullableType(); } protected bool IsDelegateConstructorCall(EXPR pExpr) { Debug.Assert(pExpr != null); if (!pExpr.isCALL()) { return false; } EXPRCALL pCall = pExpr.asCALL(); return pCall.mwi.Meth() != null && pCall.mwi.Meth().IsConstructor() && pCall.type.isDelegateType() && pCall.GetOptionalArguments() != null && pCall.GetOptionalArguments().isLIST() && pCall.GetOptionalArguments().asLIST().GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR; } private static bool isEnumToDecimalConversion(CType argtype, CType desttype) { CType strippedArgType = argtype.IsNullableType() ? argtype.StripNubs() : argtype; CType strippedDestType = desttype.IsNullableType() ? desttype.StripNubs() : desttype; return strippedArgType.isEnumType() && strippedDestType.isPredefType(PredefinedType.PT_DECIMAL); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using AutoRest.Core; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Core.Utilities.Collections; using AutoRest.Swagger.Model; using static AutoRest.Core.Utilities.DependencyInjection; namespace AutoRest.Swagger { /// <summary> /// The builder for building a generic swagger object into parameters, /// service types or Json serialization types. /// </summary> public class ObjectBuilder { protected SwaggerObject SwaggerObject { get; set; } protected SwaggerModeler Modeler { get; set; } public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler) { SwaggerObject = swaggerObject; Modeler = modeler; } public virtual IModelType ParentBuildServiceType(string serviceTypeName) { // Should not try to get parent from generic swagger object builder throw new InvalidOperationException(); } /// <summary> /// The visitor method for building service types. This is called when an instance of this class is /// visiting a _swaggerModeler to build a service type. /// </summary> /// <param name="serviceTypeName">name for the service type</param> /// <returns>built service type</returns> public virtual IModelType BuildServiceType(string serviceTypeName) { PrimaryType type = SwaggerObject.ToType(); Debug.Assert(type != null); if (type.KnownPrimaryType == KnownPrimaryType.Object && SwaggerObject.KnownFormat == KnownFormat.file ) { type = New<PrimaryType>(KnownPrimaryType.Stream); } type.XmlProperties = (SwaggerObject as Schema)?.Xml; type.Format = SwaggerObject.Format; if (SwaggerObject.Enum != null && type.KnownPrimaryType == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject))) { var enumType = New<EnumType>(); SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue { Name = v, SerializedName = v })); if (SwaggerObject.Extensions.ContainsKey(Core.Model.XmsExtensions.Enum.Name)) { var enumObject = SwaggerObject.Extensions[Core.Model.XmsExtensions.Enum.Name] as Newtonsoft.Json.Linq.JContainer; if (enumObject != null) { enumType.SetName( enumObject["name"].ToString() ); if (enumObject["modelAsString"] != null) { enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString()); } } enumType.SerializedName = enumType.Name; if (string.IsNullOrEmpty(enumType.Name)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "{0} extension needs to specify an enum name.", Core.Model.XmsExtensions.Enum.Name)); } var existingEnum = Modeler.CodeModel.EnumTypes.FirstOrDefault( e => e.Name.RawValue.EqualsIgnoreCase(enumType.Name.RawValue)); if (existingEnum != null) { if (!existingEnum.StructurallyEquals(enumType)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Swagger document contains two or more {0} extensions with the same name '{1}' and different values.", Core.Model.XmsExtensions.Enum.Name, enumType.Name)); } // Use the existing one! enumType = existingEnum; } else { Modeler.CodeModel.Add(enumType); } } else { enumType.ModelAsString = true; enumType.SetName( string.Empty); enumType.SerializedName = string.Empty; } enumType.XmlProperties = (SwaggerObject as Schema)?.Xml; return enumType; } if (SwaggerObject.Type == DataType.Array) { string itemServiceTypeName; if (SwaggerObject.Items.Reference != null) { itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath(); } else { itemServiceTypeName = serviceTypeName + "Item"; } var elementType = SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName); return New<SequenceType>(new { ElementType = elementType, Extensions = SwaggerObject.Items.Extensions, XmlProperties = (SwaggerObject as Schema)?.Xml, ElementXmlProperties = SwaggerObject.Items?.Xml }); } if (SwaggerObject.AdditionalProperties != null) { string dictionaryValueServiceTypeName; if (SwaggerObject.AdditionalProperties.Reference != null) { dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath(); } else { dictionaryValueServiceTypeName = serviceTypeName + "Value"; } return New<DictionaryType>(new { ValueType = SwaggerObject.AdditionalProperties.GetBuilder(Modeler) .BuildServiceType((dictionaryValueServiceTypeName)), Extensions = SwaggerObject.AdditionalProperties.Extensions, XmlProperties = (SwaggerObject as Schema)?.Xml }); } return type; } public static void PopulateParameter(IVariable parameter, SwaggerObject swaggerObject) { if (swaggerObject == null) { throw new ArgumentNullException("swaggerObject"); } if (parameter == null) { throw new ArgumentNullException("parameter"); } parameter.IsRequired = swaggerObject.IsRequired; parameter.DefaultValue = swaggerObject.Default; if (IsSwaggerObjectConstant(swaggerObject)) { parameter.DefaultValue = swaggerObject.Enum[0]; parameter.IsConstant = true; } parameter.Documentation = swaggerObject.Description; parameter.CollectionFormat = swaggerObject.CollectionFormat; // tag the paramter with all the extensions from the swagger object parameter.Extensions.AddRange(swaggerObject.Extensions); SetConstraints(parameter.Constraints, swaggerObject); } private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject) { return (swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired); } public static void SetConstraints(Dictionary<Constraint, string> constraints, SwaggerObject swaggerObject) { if (constraints == null) { throw new ArgumentNullException("constraints"); } if (swaggerObject == null) { throw new ArgumentNullException("swaggerObject"); } if (!string.IsNullOrEmpty(swaggerObject.Maximum) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum)) && !swaggerObject.ExclusiveMaximum) { constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum; } if (!string.IsNullOrEmpty(swaggerObject.Maximum) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum)) && swaggerObject.ExclusiveMaximum && swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMaximum))) { constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum; } if (!string.IsNullOrEmpty(swaggerObject.Minimum) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum)) && !swaggerObject.ExclusiveMinimum) { constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum; } if (!string.IsNullOrEmpty(swaggerObject.Minimum) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum)) && swaggerObject.ExclusiveMinimum && swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMinimum))) { constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum; } if (!string.IsNullOrEmpty(swaggerObject.MaxLength) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxLength))) { constraints[Constraint.MaxLength] = swaggerObject.MaxLength; } if (!string.IsNullOrEmpty(swaggerObject.MinLength) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinLength))) { constraints[Constraint.MinLength] = swaggerObject.MinLength; } if (!string.IsNullOrEmpty(swaggerObject.Pattern) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.Pattern))) { constraints[Constraint.Pattern] = swaggerObject.Pattern; } if (!string.IsNullOrEmpty(swaggerObject.MaxItems) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxItems))) { constraints[Constraint.MaxItems] = swaggerObject.MaxItems; } if (!string.IsNullOrEmpty(swaggerObject.MinItems) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinItems))) { constraints[Constraint.MinItems] = swaggerObject.MinItems; } if (!string.IsNullOrEmpty(swaggerObject.MultipleOf) && swaggerObject.IsConstraintSupported(nameof(swaggerObject.MultipleOf))) { constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf; } if (swaggerObject.UniqueItems && swaggerObject.IsConstraintSupported(nameof(swaggerObject.UniqueItems))) { constraints[Constraint.UniqueItems] = "true"; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace SampleWebApiApp.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using TableTranslator.Model.Settings; namespace TableTranslator.Helpers { internal static class ReflectionHelper { internal const BindingFlags DEFAULT_BINDING_FLAGS = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; private static readonly IEnumerable<MemberTypes> DEFAULT_MEMBER_TYPES = new List<MemberTypes> { MemberTypes.Property, MemberTypes.Field }; /// <summary> /// Gets the member from a LambdaExpression /// </summary> /// <param name="lambda">Labda expression from which to get the members information</param> /// <returns>Member info for the member in the lambda expression</returns> internal static MemberInfo GetMemberInfoFromLambda(LambdaExpression lambda) { var body = lambda.Body as MemberExpression; if (body == null) { throw new ArgumentException("The body of the lambda expression must be a MemberExpression.", nameof(lambda)); } return body.Member; } /// <summary> /// Gets the type for the member info /// </summary> /// <param name="memberInfo">Member info from which to get the type</param> /// <returns>The type of the member info</returns> internal static Type GetMemberType(this MemberInfo memberInfo) { var propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) return propertyInfo.PropertyType; var fieldInfo = memberInfo as FieldInfo; return fieldInfo?.FieldType; } /// <summary> /// Gets the type for regular types and get the underlying type for nullable value types (e.g. int? will return int) /// </summary> /// <param name="type">Type to get the pure type for</param> /// <returns>The pure type</returns> internal static Type GetPureType(this Type type) { return Nullable.GetUnderlyingType(type) ?? type; } /// <summary> /// Determines if null can be assigned to the type /// </summary> /// <param name="type">Type to check</param> /// <returns>Whenter or not null can be assigned to the type</returns> internal static bool IsNullAssignable(this Type type) { // string can be null even though it doesn't implement Nullable<> and is a value type return Nullable.GetUnderlyingType(type) != null || !type.IsValueType || type == typeof(string); } internal static IEnumerable<Type> GetTraversedGenericTypes(this Type type) { return type.GetGenericArguments().Traverse(x => x.GetGenericArguments()); } private static IEnumerable<T> Traverse<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector) { var queue = new Queue<T>(items); while (queue.Any()) { var next = queue.Dequeue(); yield return next; foreach (var child in childSelector(next)) queue.Enqueue(child); } } /// <summary> /// Formats the name of the type to be more readable (e.g. generics, enumerables, etc.) /// </summary> /// <param name="type">Type to build formatted name for</param> /// <returns>Formatted name of the type</returns> public static string BuildFormattedName(this Type type) { if (!type.IsGenericType) return type.Name; var sb = new StringBuilder(); sb.Append(type.Name.Substring(0, type.Name.IndexOf('`'))); sb.Append('<'); var appendComma = false; foreach (var arg in type.GetGenericArguments()) { if (appendComma) sb.Append(','); sb.Append(BuildFormattedName(arg)); appendComma = true; } sb.Append('>'); return sb.ToString(); } /// <summary> /// Gets the default value for the given type (reference or value types) /// </summary> /// <param name="type"></param> /// <returns></returns> internal static object GetDefaultValue(this Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; } /// <summary> /// Gets the value of the member from an object using the members relative path /// </summary> /// <param name="relativePropertyPath">Relavtive path to the object from the object passed in</param> /// <param name="obj">Object to get the member value from</param> /// <returns></returns> internal static object GetMemberValue(string relativePropertyPath, object obj) { // property path segments are separated by a '.' foreach (var pathPart in relativePropertyPath.Split('.')) { if (obj == null) { return null; } var type = obj.GetType(); obj = type.GetMemberValue(pathPart, obj); } return obj; } /// <summary> /// Gets the value of the member from an object using the member name /// </summary> /// <param name="type"></param> /// <param name="memberName">Name of the member</param> /// <param name="obj">Object to get the member value from</param> /// <returns></returns> private static object GetMemberValue(this IReflect type, string memberName, object obj) { var memberInfo = type.GetMember(memberName, DEFAULT_BINDING_FLAGS).FirstOrDefault(); if (memberInfo is PropertyInfo) { return type.GetProperty(memberName, DEFAULT_BINDING_FLAGS).GetValue(obj); } if (memberInfo is FieldInfo) { return type.GetField(memberName, DEFAULT_BINDING_FLAGS).GetValue(obj); } return null; } /// <summary> /// Gets the relative path name for a member from a lambda expression /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="lambda"></param> /// <returns></returns> internal static string GetMemberRelativePathNameFromLambda<TSource, TResult>(Expression<Func<TSource, TResult>> lambda) { return lambda.Body.ToString() .Replace($"{lambda.Parameters.First()}.", string.Empty) .Replace($"{typeof (TSource).Name}.", string.Empty); // allows us to get static members } /// <summary> /// Attempts to get a constant member from a type by using its value /// </summary> /// <typeparam name="T">Type the constant belongs to</typeparam> /// <typeparam name="K">Type of the constant</typeparam> /// <param name="valueToCompare">Value of the constant</param> /// <param name="memberInfo">MemberInfo of the constant (output parameter)</param> /// <returns></returns> internal static bool TryGetConstantMemberInfoByValue<T, K>(K valueToCompare, out MemberInfo memberInfo) where T : new() { var matchingConstants = typeof (T).GetFields(DEFAULT_BINDING_FLAGS) .Where(x => { if (!x.IsLiteral || x.GetMemberType() != typeof(K)) return false; // constants of type K only var constValue = (K) typeof (T).GetMemberValue(x.Name, new T()); return EqualityComparer<K>.Default.Equals(valueToCompare, constValue); // constant value equals value that was passed in }).ToList(); // it is conceivable that more than one constant of type K could have the same value memberInfo = matchingConstants.Count == 1 ? matchingConstants.First() : null; return memberInfo != null; } /// <summary> /// Gets all property and field members of type T that match the provided settings /// </summary> /// <typeparam name="T">Type to get members of</typeparam> /// <param name="getAllMemberSettings">Settings for which members to get</param> /// <returns></returns> internal static IEnumerable<MemberInfo> GetAllMembers<T>(GetAllMemberSettings getAllMemberSettings) where T : new() { var members = typeof (T).GetMembers(getAllMemberSettings.BindingFlags) .Where(x => DEFAULT_MEMBER_TYPES.Contains(x.MemberType) // only get properties and fields (e.g. no methods, etc.) && (!x.GetCustomAttributes().Any(y => y is CompilerGeneratedAttribute)) // don't get compiler generated members (e.g. backing fields) && (x.GetMemberType().IsValueType || x.GetMemberType() == typeof(string)) // don't get complex types && (getAllMemberSettings.Predicate == null || getAllMemberSettings.Predicate(x))); return getAllMemberSettings.Orderer != null ? members.OrderBy(x => x, getAllMemberSettings.Orderer) : members; } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="none" email=""/> // <version>$Revision: 3715 $</version> // </file> using System; using System.IO; using NUnit.Framework; using ICSharpCode.NRefactory.Parser; using ICSharpCode.NRefactory.Parser.CSharp; using ICSharpCode.NRefactory.PrettyPrinter; namespace ICSharpCode.NRefactory.Tests.Lexer.CSharp { [TestFixture] public sealed class LexerTests { ILexer GenerateLexer(StringReader sr) { return ParserFactory.CreateLexer(SupportedLanguage.CSharp, sr); } [Test] public void TestAssign() { ILexer lexer = GenerateLexer(new StringReader("=")); Assert.AreEqual(Tokens.Assign, lexer.NextToken().Kind); } [Test] public void TestPlus() { ILexer lexer = GenerateLexer(new StringReader("+")); Assert.AreEqual(Tokens.Plus, lexer.NextToken().Kind); } [Test] public void TestMinus() { ILexer lexer = GenerateLexer(new StringReader("-")); Assert.AreEqual(Tokens.Minus, lexer.NextToken().Kind); } [Test] public void TestTimes() { ILexer lexer = GenerateLexer(new StringReader("*")); Assert.AreEqual(Tokens.Times, lexer.NextToken().Kind); } [Test] public void TestDiv() { ILexer lexer = GenerateLexer(new StringReader("/")); Assert.AreEqual(Tokens.Div, lexer.NextToken().Kind); } [Test] public void TestMod() { ILexer lexer = GenerateLexer(new StringReader("%")); Assert.AreEqual(Tokens.Mod, lexer.NextToken().Kind); } [Test] public void TestColon() { ILexer lexer = GenerateLexer(new StringReader(":")); Assert.AreEqual(Tokens.Colon, lexer.NextToken().Kind); } [Test] public void TestDoubleColon() { ILexer lexer = GenerateLexer(new StringReader("::")); Assert.AreEqual(Tokens.DoubleColon, lexer.NextToken().Kind); } [Test] public void TestSemicolon() { ILexer lexer = GenerateLexer(new StringReader(";")); Assert.AreEqual(Tokens.Semicolon, lexer.NextToken().Kind); } [Test] public void TestQuestion() { ILexer lexer = GenerateLexer(new StringReader("?")); Assert.AreEqual(Tokens.Question, lexer.NextToken().Kind); } [Test] public void TestDoubleQuestion() { ILexer lexer = GenerateLexer(new StringReader("??")); Assert.AreEqual(Tokens.DoubleQuestion, lexer.NextToken().Kind); } [Test] public void TestComma() { ILexer lexer = GenerateLexer(new StringReader(",")); Assert.AreEqual(Tokens.Comma, lexer.NextToken().Kind); } [Test] public void TestDot() { ILexer lexer = GenerateLexer(new StringReader(".")); Assert.AreEqual(Tokens.Dot, lexer.NextToken().Kind); } [Test] public void TestOpenCurlyBrace() { ILexer lexer = GenerateLexer(new StringReader("{")); Assert.AreEqual(Tokens.OpenCurlyBrace, lexer.NextToken().Kind); } [Test] public void TestCloseCurlyBrace() { ILexer lexer = GenerateLexer(new StringReader("}")); Assert.AreEqual(Tokens.CloseCurlyBrace, lexer.NextToken().Kind); } [Test] public void TestOpenSquareBracket() { ILexer lexer = GenerateLexer(new StringReader("[")); Assert.AreEqual(Tokens.OpenSquareBracket, lexer.NextToken().Kind); } [Test] public void TestCloseSquareBracket() { ILexer lexer = GenerateLexer(new StringReader("]")); Assert.AreEqual(Tokens.CloseSquareBracket, lexer.NextToken().Kind); } [Test] public void TestOpenParenthesis() { ILexer lexer = GenerateLexer(new StringReader("(")); Assert.AreEqual(Tokens.OpenParenthesis, lexer.NextToken().Kind); } [Test] public void TestCloseParenthesis() { ILexer lexer = GenerateLexer(new StringReader(")")); Assert.AreEqual(Tokens.CloseParenthesis, lexer.NextToken().Kind); } [Test] public void TestGreaterThan() { ILexer lexer = GenerateLexer(new StringReader(">")); Assert.AreEqual(Tokens.GreaterThan, lexer.NextToken().Kind); } [Test] public void TestLessThan() { ILexer lexer = GenerateLexer(new StringReader("<")); Assert.AreEqual(Tokens.LessThan, lexer.NextToken().Kind); } [Test] public void TestNot() { ILexer lexer = GenerateLexer(new StringReader("!")); Assert.AreEqual(Tokens.Not, lexer.NextToken().Kind); } [Test] public void TestLogicalAnd() { ILexer lexer = GenerateLexer(new StringReader("&&")); Assert.AreEqual(Tokens.LogicalAnd, lexer.NextToken().Kind); } [Test] public void TestLogicalOr() { ILexer lexer = GenerateLexer(new StringReader("||")); Assert.AreEqual(Tokens.LogicalOr, lexer.NextToken().Kind); } [Test] public void TestBitwiseComplement() { ILexer lexer = GenerateLexer(new StringReader("~")); Assert.AreEqual(Tokens.BitwiseComplement, lexer.NextToken().Kind); } [Test] public void TestBitwiseAnd() { ILexer lexer = GenerateLexer(new StringReader("&")); Assert.AreEqual(Tokens.BitwiseAnd, lexer.NextToken().Kind); } [Test] public void TestBitwiseOr() { ILexer lexer = GenerateLexer(new StringReader("|")); Assert.AreEqual(Tokens.BitwiseOr, lexer.NextToken().Kind); } [Test] public void TestXor() { ILexer lexer = GenerateLexer(new StringReader("^")); Assert.AreEqual(Tokens.Xor, lexer.NextToken().Kind); } [Test] public void TestIncrement() { ILexer lexer = GenerateLexer(new StringReader("++")); Assert.AreEqual(Tokens.Increment, lexer.NextToken().Kind); } [Test] public void TestDecrement() { ILexer lexer = GenerateLexer(new StringReader("--")); Assert.AreEqual(Tokens.Decrement, lexer.NextToken().Kind); } [Test] public void TestEqual() { ILexer lexer = GenerateLexer(new StringReader("==")); Assert.AreEqual(Tokens.Equal, lexer.NextToken().Kind); } [Test] public void TestNotEqual() { ILexer lexer = GenerateLexer(new StringReader("!=")); Assert.AreEqual(Tokens.NotEqual, lexer.NextToken().Kind); } [Test] public void TestGreaterEqual() { ILexer lexer = GenerateLexer(new StringReader(">=")); Assert.AreEqual(Tokens.GreaterEqual, lexer.NextToken().Kind); } [Test] public void TestLessEqual() { ILexer lexer = GenerateLexer(new StringReader("<=")); Assert.AreEqual(Tokens.LessEqual, lexer.NextToken().Kind); } [Test] public void TestShiftLeft() { ILexer lexer = GenerateLexer(new StringReader("<<")); Assert.AreEqual(Tokens.ShiftLeft, lexer.NextToken().Kind); } [Test] public void TestPlusAssign() { ILexer lexer = GenerateLexer(new StringReader("+=")); Assert.AreEqual(Tokens.PlusAssign, lexer.NextToken().Kind); } [Test] public void TestMinusAssign() { ILexer lexer = GenerateLexer(new StringReader("-=")); Assert.AreEqual(Tokens.MinusAssign, lexer.NextToken().Kind); } [Test] public void TestTimesAssign() { ILexer lexer = GenerateLexer(new StringReader("*=")); Assert.AreEqual(Tokens.TimesAssign, lexer.NextToken().Kind); } [Test] public void TestDivAssign() { ILexer lexer = GenerateLexer(new StringReader("/=")); Assert.AreEqual(Tokens.DivAssign, lexer.NextToken().Kind); } [Test] public void TestModAssign() { ILexer lexer = GenerateLexer(new StringReader("%=")); Assert.AreEqual(Tokens.ModAssign, lexer.NextToken().Kind); } [Test] public void TestBitwiseAndAssign() { ILexer lexer = GenerateLexer(new StringReader("&=")); Assert.AreEqual(Tokens.BitwiseAndAssign, lexer.NextToken().Kind); } [Test] public void TestBitwiseOrAssign() { ILexer lexer = GenerateLexer(new StringReader("|=")); Assert.AreEqual(Tokens.BitwiseOrAssign, lexer.NextToken().Kind); } [Test] public void TestXorAssign() { ILexer lexer = GenerateLexer(new StringReader("^=")); Assert.AreEqual(Tokens.XorAssign, lexer.NextToken().Kind); } [Test] public void TestShiftLeftAssign() { ILexer lexer = GenerateLexer(new StringReader("<<=")); Assert.AreEqual(Tokens.ShiftLeftAssign, lexer.NextToken().Kind); } [Test] public void TestPointer() { ILexer lexer = GenerateLexer(new StringReader("->")); Assert.AreEqual(Tokens.Pointer, lexer.NextToken().Kind); } [Test] public void TestLambdaArrow() { ILexer lexer = GenerateLexer(new StringReader("=>")); Assert.AreEqual(Tokens.LambdaArrow, lexer.NextToken().Kind); } [Test()] public void TestAbstract() { ILexer lexer = GenerateLexer(new StringReader("abstract")); Assert.AreEqual(Tokens.Abstract, lexer.NextToken().Kind); } [Test()] public void TestAs() { ILexer lexer = GenerateLexer(new StringReader("as")); Assert.AreEqual(Tokens.As, lexer.NextToken().Kind); } [Test()] public void TestBase() { ILexer lexer = GenerateLexer(new StringReader("base")); Assert.AreEqual(Tokens.Base, lexer.NextToken().Kind); } [Test()] public void TestBool() { ILexer lexer = GenerateLexer(new StringReader("bool")); Assert.AreEqual(Tokens.Bool, lexer.NextToken().Kind); } [Test()] public void TestBreak() { ILexer lexer = GenerateLexer(new StringReader("break")); Assert.AreEqual(Tokens.Break, lexer.NextToken().Kind); } [Test()] public void TestByte() { ILexer lexer = GenerateLexer(new StringReader("byte")); Assert.AreEqual(Tokens.Byte, lexer.NextToken().Kind); } [Test()] public void TestCase() { ILexer lexer = GenerateLexer(new StringReader("case")); Assert.AreEqual(Tokens.Case, lexer.NextToken().Kind); } [Test()] public void TestCatch() { ILexer lexer = GenerateLexer(new StringReader("catch")); Assert.AreEqual(Tokens.Catch, lexer.NextToken().Kind); } [Test()] public void TestChar() { ILexer lexer = GenerateLexer(new StringReader("char")); Assert.AreEqual(Tokens.Char, lexer.NextToken().Kind); } [Test()] public void TestChecked() { ILexer lexer = GenerateLexer(new StringReader("checked")); Assert.AreEqual(Tokens.Checked, lexer.NextToken().Kind); } [Test()] public void TestClass() { ILexer lexer = GenerateLexer(new StringReader("class")); Assert.AreEqual(Tokens.Class, lexer.NextToken().Kind); } [Test()] public void TestConst() { ILexer lexer = GenerateLexer(new StringReader("const")); Assert.AreEqual(Tokens.Const, lexer.NextToken().Kind); } [Test()] public void TestContinue() { ILexer lexer = GenerateLexer(new StringReader("continue")); Assert.AreEqual(Tokens.Continue, lexer.NextToken().Kind); } [Test()] public void TestDecimal() { ILexer lexer = GenerateLexer(new StringReader("decimal")); Assert.AreEqual(Tokens.Decimal, lexer.NextToken().Kind); } [Test()] public void TestDefault() { ILexer lexer = GenerateLexer(new StringReader("default")); Assert.AreEqual(Tokens.Default, lexer.NextToken().Kind); } [Test()] public void TestDelegate() { ILexer lexer = GenerateLexer(new StringReader("delegate")); Assert.AreEqual(Tokens.Delegate, lexer.NextToken().Kind); } [Test()] public void TestDo() { ILexer lexer = GenerateLexer(new StringReader("do")); Assert.AreEqual(Tokens.Do, lexer.NextToken().Kind); } [Test()] public void TestDouble() { ILexer lexer = GenerateLexer(new StringReader("double")); Assert.AreEqual(Tokens.Double, lexer.NextToken().Kind); } [Test()] public void TestElse() { ILexer lexer = GenerateLexer(new StringReader("else")); Assert.AreEqual(Tokens.Else, lexer.NextToken().Kind); } [Test()] public void TestEnum() { ILexer lexer = GenerateLexer(new StringReader("enum")); Assert.AreEqual(Tokens.Enum, lexer.NextToken().Kind); } [Test()] public void TestEvent() { ILexer lexer = GenerateLexer(new StringReader("event")); Assert.AreEqual(Tokens.Event, lexer.NextToken().Kind); } [Test()] public void TestExplicit() { ILexer lexer = GenerateLexer(new StringReader("explicit")); Assert.AreEqual(Tokens.Explicit, lexer.NextToken().Kind); } [Test()] public void TestExtern() { ILexer lexer = GenerateLexer(new StringReader("extern")); Assert.AreEqual(Tokens.Extern, lexer.NextToken().Kind); } [Test()] public void TestFalse() { ILexer lexer = GenerateLexer(new StringReader("false")); Assert.AreEqual(Tokens.False, lexer.NextToken().Kind); } [Test()] public void TestFinally() { ILexer lexer = GenerateLexer(new StringReader("finally")); Assert.AreEqual(Tokens.Finally, lexer.NextToken().Kind); } [Test()] public void TestFixed() { ILexer lexer = GenerateLexer(new StringReader("fixed")); Assert.AreEqual(Tokens.Fixed, lexer.NextToken().Kind); } [Test()] public void TestFloat() { ILexer lexer = GenerateLexer(new StringReader("float")); Assert.AreEqual(Tokens.Float, lexer.NextToken().Kind); } [Test()] public void TestFor() { ILexer lexer = GenerateLexer(new StringReader("for")); Assert.AreEqual(Tokens.For, lexer.NextToken().Kind); } [Test()] public void TestForeach() { ILexer lexer = GenerateLexer(new StringReader("foreach")); Assert.AreEqual(Tokens.Foreach, lexer.NextToken().Kind); } [Test()] public void TestGoto() { ILexer lexer = GenerateLexer(new StringReader("goto")); Assert.AreEqual(Tokens.Goto, lexer.NextToken().Kind); } [Test()] public void TestIf() { ILexer lexer = GenerateLexer(new StringReader("if")); Assert.AreEqual(Tokens.If, lexer.NextToken().Kind); } [Test()] public void TestImplicit() { ILexer lexer = GenerateLexer(new StringReader("implicit")); Assert.AreEqual(Tokens.Implicit, lexer.NextToken().Kind); } [Test()] public void TestIn() { ILexer lexer = GenerateLexer(new StringReader("in")); Assert.AreEqual(Tokens.In, lexer.NextToken().Kind); } [Test()] public void TestInt() { ILexer lexer = GenerateLexer(new StringReader("int")); Assert.AreEqual(Tokens.Int, lexer.NextToken().Kind); } [Test()] public void TestInterface() { ILexer lexer = GenerateLexer(new StringReader("interface")); Assert.AreEqual(Tokens.Interface, lexer.NextToken().Kind); } [Test()] public void TestInternal() { ILexer lexer = GenerateLexer(new StringReader("internal")); Assert.AreEqual(Tokens.Internal, lexer.NextToken().Kind); } [Test()] public void TestIs() { ILexer lexer = GenerateLexer(new StringReader("is")); Assert.AreEqual(Tokens.Is, lexer.NextToken().Kind); } [Test()] public void TestLock() { ILexer lexer = GenerateLexer(new StringReader("lock")); Assert.AreEqual(Tokens.Lock, lexer.NextToken().Kind); } [Test()] public void TestLong() { ILexer lexer = GenerateLexer(new StringReader("long")); Assert.AreEqual(Tokens.Long, lexer.NextToken().Kind); } [Test()] public void TestNamespace() { ILexer lexer = GenerateLexer(new StringReader("namespace")); Assert.AreEqual(Tokens.Namespace, lexer.NextToken().Kind); } [Test()] public void TestNew() { ILexer lexer = GenerateLexer(new StringReader("new")); Assert.AreEqual(Tokens.New, lexer.NextToken().Kind); } [Test()] public void TestNull() { ILexer lexer = GenerateLexer(new StringReader("null")); Assert.AreEqual(Tokens.Null, lexer.NextToken().Kind); } [Test()] public void TestObject() { ILexer lexer = GenerateLexer(new StringReader("object")); Assert.AreEqual(Tokens.Object, lexer.NextToken().Kind); } [Test()] public void TestOperator() { ILexer lexer = GenerateLexer(new StringReader("operator")); Assert.AreEqual(Tokens.Operator, lexer.NextToken().Kind); } [Test()] public void TestOut() { ILexer lexer = GenerateLexer(new StringReader("out")); Assert.AreEqual(Tokens.Out, lexer.NextToken().Kind); } [Test()] public void TestOverride() { ILexer lexer = GenerateLexer(new StringReader("override")); Assert.AreEqual(Tokens.Override, lexer.NextToken().Kind); } [Test()] public void TestParams() { ILexer lexer = GenerateLexer(new StringReader("params")); Assert.AreEqual(Tokens.Params, lexer.NextToken().Kind); } [Test()] public void TestPrivate() { ILexer lexer = GenerateLexer(new StringReader("private")); Assert.AreEqual(Tokens.Private, lexer.NextToken().Kind); } [Test()] public void TestProtected() { ILexer lexer = GenerateLexer(new StringReader("protected")); Assert.AreEqual(Tokens.Protected, lexer.NextToken().Kind); } [Test()] public void TestPublic() { ILexer lexer = GenerateLexer(new StringReader("public")); Assert.AreEqual(Tokens.Public, lexer.NextToken().Kind); } [Test()] public void TestReadonly() { ILexer lexer = GenerateLexer(new StringReader("readonly")); Assert.AreEqual(Tokens.Readonly, lexer.NextToken().Kind); } [Test()] public void TestRef() { ILexer lexer = GenerateLexer(new StringReader("ref")); Assert.AreEqual(Tokens.Ref, lexer.NextToken().Kind); } [Test()] public void TestReturn() { ILexer lexer = GenerateLexer(new StringReader("return")); Assert.AreEqual(Tokens.Return, lexer.NextToken().Kind); } [Test()] public void TestSbyte() { ILexer lexer = GenerateLexer(new StringReader("sbyte")); Assert.AreEqual(Tokens.Sbyte, lexer.NextToken().Kind); } [Test()] public void TestSealed() { ILexer lexer = GenerateLexer(new StringReader("sealed")); Assert.AreEqual(Tokens.Sealed, lexer.NextToken().Kind); } [Test()] public void TestShort() { ILexer lexer = GenerateLexer(new StringReader("short")); Assert.AreEqual(Tokens.Short, lexer.NextToken().Kind); } [Test()] public void TestSizeof() { ILexer lexer = GenerateLexer(new StringReader("sizeof")); Assert.AreEqual(Tokens.Sizeof, lexer.NextToken().Kind); } [Test()] public void TestStackalloc() { ILexer lexer = GenerateLexer(new StringReader("stackalloc")); Assert.AreEqual(Tokens.Stackalloc, lexer.NextToken().Kind); } [Test()] public void TestStatic() { ILexer lexer = GenerateLexer(new StringReader("static")); Assert.AreEqual(Tokens.Static, lexer.NextToken().Kind); } [Test()] public void TestString() { ILexer lexer = GenerateLexer(new StringReader("string")); Assert.AreEqual(Tokens.String, lexer.NextToken().Kind); } [Test()] public void TestStruct() { ILexer lexer = GenerateLexer(new StringReader("struct")); Assert.AreEqual(Tokens.Struct, lexer.NextToken().Kind); } [Test()] public void TestSwitch() { ILexer lexer = GenerateLexer(new StringReader("switch")); Assert.AreEqual(Tokens.Switch, lexer.NextToken().Kind); } [Test()] public void TestThis() { ILexer lexer = GenerateLexer(new StringReader("this")); Assert.AreEqual(Tokens.This, lexer.NextToken().Kind); } [Test()] public void TestThrow() { ILexer lexer = GenerateLexer(new StringReader("throw")); Assert.AreEqual(Tokens.Throw, lexer.NextToken().Kind); } [Test()] public void TestTrue() { ILexer lexer = GenerateLexer(new StringReader("true")); Assert.AreEqual(Tokens.True, lexer.NextToken().Kind); } [Test()] public void TestTry() { ILexer lexer = GenerateLexer(new StringReader("try")); Assert.AreEqual(Tokens.Try, lexer.NextToken().Kind); } [Test()] public void TestTypeof() { ILexer lexer = GenerateLexer(new StringReader("typeof")); Assert.AreEqual(Tokens.Typeof, lexer.NextToken().Kind); } [Test()] public void TestUint() { ILexer lexer = GenerateLexer(new StringReader("uint")); Assert.AreEqual(Tokens.Uint, lexer.NextToken().Kind); } [Test()] public void TestUlong() { ILexer lexer = GenerateLexer(new StringReader("ulong")); Assert.AreEqual(Tokens.Ulong, lexer.NextToken().Kind); } [Test()] public void TestUnchecked() { ILexer lexer = GenerateLexer(new StringReader("unchecked")); Assert.AreEqual(Tokens.Unchecked, lexer.NextToken().Kind); } [Test()] public void TestUnsafe() { ILexer lexer = GenerateLexer(new StringReader("unsafe")); Assert.AreEqual(Tokens.Unsafe, lexer.NextToken().Kind); } [Test()] public void TestUshort() { ILexer lexer = GenerateLexer(new StringReader("ushort")); Assert.AreEqual(Tokens.Ushort, lexer.NextToken().Kind); } [Test()] public void TestUsing() { ILexer lexer = GenerateLexer(new StringReader("using")); Assert.AreEqual(Tokens.Using, lexer.NextToken().Kind); } [Test()] public void TestVirtual() { ILexer lexer = GenerateLexer(new StringReader("virtual")); Assert.AreEqual(Tokens.Virtual, lexer.NextToken().Kind); } [Test()] public void TestVoid() { ILexer lexer = GenerateLexer(new StringReader("void")); Assert.AreEqual(Tokens.Void, lexer.NextToken().Kind); } [Test()] public void TestVolatile() { ILexer lexer = GenerateLexer(new StringReader("volatile")); Assert.AreEqual(Tokens.Volatile, lexer.NextToken().Kind); } [Test()] public void TestWhile() { ILexer lexer = GenerateLexer(new StringReader("while")); Assert.AreEqual(Tokens.While, lexer.NextToken().Kind); } [Test()] public void TestPartial() { ILexer lexer = GenerateLexer(new StringReader("partial")); Assert.AreEqual(Tokens.Partial, lexer.NextToken().Kind); } [Test()] public void TestWhere() { ILexer lexer = GenerateLexer(new StringReader("where")); Assert.AreEqual(Tokens.Where, lexer.NextToken().Kind); } [Test()] public void TestGet() { ILexer lexer = GenerateLexer(new StringReader("get")); Assert.AreEqual(Tokens.Get, lexer.NextToken().Kind); } [Test()] public void TestSet() { ILexer lexer = GenerateLexer(new StringReader("set")); Assert.AreEqual(Tokens.Set, lexer.NextToken().Kind); } [Test()] public void TestAdd() { ILexer lexer = GenerateLexer(new StringReader("add")); Assert.AreEqual(Tokens.Add, lexer.NextToken().Kind); } [Test()] public void TestRemove() { ILexer lexer = GenerateLexer(new StringReader("remove")); Assert.AreEqual(Tokens.Remove, lexer.NextToken().Kind); } [Test()] public void TestYield() { ILexer lexer = GenerateLexer(new StringReader("yield")); Assert.AreEqual(Tokens.Yield, lexer.NextToken().Kind); } [Test()] public void TestSelect() { ILexer lexer = GenerateLexer(new StringReader("select")); Assert.AreEqual(Tokens.Select, lexer.NextToken().Kind); } [Test()] public void TestGroup() { ILexer lexer = GenerateLexer(new StringReader("group")); Assert.AreEqual(Tokens.Group, lexer.NextToken().Kind); } [Test()] public void TestBy() { ILexer lexer = GenerateLexer(new StringReader("by")); Assert.AreEqual(Tokens.By, lexer.NextToken().Kind); } [Test()] public void TestInto() { ILexer lexer = GenerateLexer(new StringReader("into")); Assert.AreEqual(Tokens.Into, lexer.NextToken().Kind); } [Test()] public void TestFrom() { ILexer lexer = GenerateLexer(new StringReader("from")); Assert.AreEqual(Tokens.From, lexer.NextToken().Kind); } [Test()] public void TestAscending() { ILexer lexer = GenerateLexer(new StringReader("ascending")); Assert.AreEqual(Tokens.Ascending, lexer.NextToken().Kind); } [Test()] public void TestDescending() { ILexer lexer = GenerateLexer(new StringReader("descending")); Assert.AreEqual(Tokens.Descending, lexer.NextToken().Kind); } [Test()] public void TestOrderby() { ILexer lexer = GenerateLexer(new StringReader("orderby")); Assert.AreEqual(Tokens.Orderby, lexer.NextToken().Kind); } } }
using J2N.Text; using YAF.Lucene.Net.Analysis.TokenAttributes; using YAF.Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace YAF.Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FieldsConsumer = YAF.Lucene.Net.Codecs.FieldsConsumer; using FixedBitSet = YAF.Lucene.Net.Util.FixedBitSet; using OffsetAttribute = YAF.Lucene.Net.Analysis.TokenAttributes.OffsetAttribute; using PayloadAttribute = YAF.Lucene.Net.Analysis.TokenAttributes.PayloadAttribute; using PostingsConsumer = YAF.Lucene.Net.Codecs.PostingsConsumer; using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator; using TermsConsumer = YAF.Lucene.Net.Codecs.TermsConsumer; using TermStats = YAF.Lucene.Net.Codecs.TermStats; // TODO: break into separate freq and prox writers as // codecs; make separate container (tii/tis/skip/*) that can // be configured as any number of files 1..N internal sealed class FreqProxTermsWriterPerField : TermsHashConsumerPerField, IComparable<FreqProxTermsWriterPerField> { internal readonly FreqProxTermsWriter parent; internal readonly TermsHashPerField termsHashPerField; internal readonly FieldInfo fieldInfo; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly FieldInvertState fieldState; private bool hasFreq; private bool hasProx; private bool hasOffsets; internal IPayloadAttribute payloadAttribute; internal IOffsetAttribute offsetAttribute; public FreqProxTermsWriterPerField(TermsHashPerField termsHashPerField, FreqProxTermsWriter parent, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.parent = parent; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; SetIndexOptions(fieldInfo.IndexOptions); } internal override int StreamCount { get { if (!hasProx) { return 1; } else { return 2; } } } internal override void Finish() { if (hasPayloads) { fieldInfo.SetStorePayloads(); } } internal bool hasPayloads; [ExceptionToNetNumericConvention] internal override void SkippingLongTerm() { } public int CompareTo(FreqProxTermsWriterPerField other) { return fieldInfo.Name.CompareToOrdinal(other.fieldInfo.Name); } // Called after flush internal void Reset() { // Record, up front, whether our in-RAM format will be // with or without term freqs: SetIndexOptions(fieldInfo.IndexOptions); payloadAttribute = null; } private void SetIndexOptions(IndexOptions indexOptions) { if (indexOptions == IndexOptions.NONE) { // field could later be updated with indexed=true, so set everything on hasFreq = hasProx = hasOffsets = true; } else { hasFreq = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; hasProx = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; hasOffsets = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } } internal override bool Start(IIndexableField[] fields, int count) { for (int i = 0; i < count; i++) { if (fields[i].IndexableFieldType.IsIndexed) { return true; } } return false; } internal override void Start(IIndexableField f) { if (fieldState.AttributeSource.HasAttribute<IPayloadAttribute>()) { payloadAttribute = fieldState.AttributeSource.GetAttribute<IPayloadAttribute>(); } else { payloadAttribute = null; } if (hasOffsets) { offsetAttribute = fieldState.AttributeSource.AddAttribute<IOffsetAttribute>(); } else { offsetAttribute = null; } } internal void WriteProx(int termID, int proxCode) { //System.out.println("writeProx termID=" + termID + " proxCode=" + proxCode); Debug.Assert(hasProx); BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.Payload; } if (payload != null && payload.Length > 0) { termsHashPerField.WriteVInt32(1, (proxCode << 1) | 1); termsHashPerField.WriteVInt32(1, payload.Length); termsHashPerField.WriteBytes(1, payload.Bytes, payload.Offset, payload.Length); hasPayloads = true; } else { termsHashPerField.WriteVInt32(1, proxCode << 1); } FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastPositions[termID] = fieldState.Position; } internal void WriteOffsets(int termID, int offsetAccum) { Debug.Assert(hasOffsets); int startOffset = offsetAccum + offsetAttribute.StartOffset; int endOffset = offsetAccum + offsetAttribute.EndOffset; FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; Debug.Assert(startOffset - postings.lastOffsets[termID] >= 0); termsHashPerField.WriteVInt32(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.WriteVInt32(1, endOffset - startOffset); postings.lastOffsets[termID] = startOffset; } internal override void NewTerm(int termID) { // First time we're seeing this term since the last // flush Debug.Assert(docState.TestPoint("FreqProxTermsWriterPerField.newTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastDocIDs[termID] = docState.docID; if (!hasFreq) { postings.lastDocCodes[termID] = docState.docID; } else { postings.lastDocCodes[termID] = docState.docID << 1; postings.termFreqs[termID] = 1; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } else { Debug.Assert(!hasOffsets); } } fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); fieldState.UniqueTermCount++; } internal override void AddTerm(int termID) { Debug.Assert(docState.TestPoint("FreqProxTermsWriterPerField.addTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; Debug.Assert(!hasFreq || postings.termFreqs[termID] > 0); if (!hasFreq) { Debug.Assert(postings.termFreqs == null); if (docState.docID != postings.lastDocIDs[termID]) { Debug.Assert(docState.docID > postings.lastDocIDs[termID]); termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); postings.lastDocCodes[termID] = docState.docID - postings.lastDocIDs[termID]; postings.lastDocIDs[termID] = docState.docID; fieldState.UniqueTermCount++; } } else if (docState.docID != postings.lastDocIDs[termID]) { Debug.Assert(docState.docID > postings.lastDocIDs[termID], "id: " + docState.docID + " postings ID: " + postings.lastDocIDs[termID] + " termID: " + termID); // Term not yet seen in the current doc but previously // seen in other doc(s) since the last flush // Now that we know doc freq for previous doc, // write it & lastDocCode if (1 == postings.termFreqs[termID]) { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID] | 1); } else { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); termsHashPerField.WriteVInt32(0, postings.termFreqs[termID]); } postings.termFreqs[termID] = 1; fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); postings.lastDocCodes[termID] = (docState.docID - postings.lastDocIDs[termID]) << 1; postings.lastDocIDs[termID] = docState.docID; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { postings.lastOffsets[termID] = 0; WriteOffsets(termID, fieldState.Offset); } } else { Debug.Assert(!hasOffsets); } fieldState.UniqueTermCount++; } else { fieldState.MaxTermFrequency = Math.Max(fieldState.MaxTermFrequency, ++postings.termFreqs[termID]); if (hasProx) { WriteProx(termID, fieldState.Position - postings.lastPositions[termID]); } if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } } internal override ParallelPostingsArray CreatePostingsArray(int size) { return new FreqProxPostingsArray(size, hasFreq, hasProx, hasOffsets); } internal sealed class FreqProxPostingsArray : ParallelPostingsArray { public FreqProxPostingsArray(int size, bool writeFreqs, bool writeProx, bool writeOffsets) : base(size) { if (writeFreqs) { termFreqs = new int[size]; } lastDocIDs = new int[size]; lastDocCodes = new int[size]; if (writeProx) { lastPositions = new int[size]; if (writeOffsets) { lastOffsets = new int[size]; } } else { Debug.Assert(!writeOffsets); } //System.out.println("PA init freqs=" + writeFreqs + " pos=" + writeProx + " offs=" + writeOffsets); } internal int[] termFreqs; // # times this term occurs in the current doc internal int[] lastDocIDs; // Last docID where this term occurred internal int[] lastDocCodes; // Code for prior doc internal int[] lastPositions; // Last position where this term occurred internal int[] lastOffsets; // Last endOffset where this term occurred internal override ParallelPostingsArray NewInstance(int size) { return new FreqProxPostingsArray(size, termFreqs != null, lastPositions != null, lastOffsets != null); } internal override void CopyTo(ParallelPostingsArray toArray, int numToCopy) { Debug.Assert(toArray is FreqProxPostingsArray); FreqProxPostingsArray to = (FreqProxPostingsArray)toArray; base.CopyTo(toArray, numToCopy); Array.Copy(lastDocIDs, 0, to.lastDocIDs, 0, numToCopy); Array.Copy(lastDocCodes, 0, to.lastDocCodes, 0, numToCopy); if (lastPositions != null) { Debug.Assert(to.lastPositions != null); Array.Copy(lastPositions, 0, to.lastPositions, 0, numToCopy); } if (lastOffsets != null) { Debug.Assert(to.lastOffsets != null); Array.Copy(lastOffsets, 0, to.lastOffsets, 0, numToCopy); } if (termFreqs != null) { Debug.Assert(to.termFreqs != null); Array.Copy(termFreqs, 0, to.termFreqs, 0, numToCopy); } } internal override int BytesPerPosting() { int bytes = ParallelPostingsArray.BYTES_PER_POSTING + 2 * RamUsageEstimator.NUM_BYTES_INT32; if (lastPositions != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (lastOffsets != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (termFreqs != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } return bytes; } } [MethodImpl(MethodImplOptions.NoInlining)] public void Abort() { } internal BytesRef payload; /// <summary> /// Walk through all unique text tokens (Posting /// instances) found in this field and serialize them /// into a single RAM segment. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal void Flush(string fieldName, FieldsConsumer consumer, SegmentWriteState state) { if (!fieldInfo.IsIndexed) { return; // nothing to flush, don't bother the codec with the unindexed field } TermsConsumer termsConsumer = consumer.AddField(fieldInfo); IComparer<BytesRef> termComp = termsConsumer.Comparer; // CONFUSING: this.indexOptions holds the index options // that were current when we first saw this field. But // it's possible this has changed, eg when other // documents are indexed that cause a "downgrade" of the // IndexOptions. So we must decode the in-RAM buffer // according to this.indexOptions, but then write the // new segment to the directory according to // currentFieldIndexOptions: IndexOptions currentFieldIndexOptions = fieldInfo.IndexOptions; Debug.Assert(currentFieldIndexOptions != IndexOptions.NONE); bool writeTermFreq = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; bool writePositions = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; bool writeOffsets = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; bool readTermFreq = this.hasFreq; bool readPositions = this.hasProx; bool readOffsets = this.hasOffsets; //System.out.println("flush readTF=" + readTermFreq + " readPos=" + readPositions + " readOffs=" + readOffsets); // Make sure FieldInfo.update is working correctly!: Debug.Assert(!writeTermFreq || readTermFreq); Debug.Assert(!writePositions || readPositions); Debug.Assert(!writeOffsets || readOffsets); Debug.Assert(!writeOffsets || writePositions); IDictionary<Term, int?> segDeletes; if (state.SegUpdates != null && state.SegUpdates.terms.Count > 0) { segDeletes = state.SegUpdates.terms; } else { segDeletes = null; } int[] termIDs = termsHashPerField.SortPostings(termComp); int numTerms = termsHashPerField.bytesHash.Count; BytesRef text = new BytesRef(); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; ByteSliceReader freq = new ByteSliceReader(); ByteSliceReader prox = new ByteSliceReader(); FixedBitSet visitedDocs = new FixedBitSet(state.SegmentInfo.DocCount); long sumTotalTermFreq = 0; long sumDocFreq = 0; Term protoTerm = new Term(fieldName); for (int i = 0; i < numTerms; i++) { int termID = termIDs[i]; // Get BytesRef int textStart = postings.textStarts[termID]; termsHashPerField.bytePool.SetBytesRef(text, textStart); termsHashPerField.InitReader(freq, termID, 0); if (readPositions || readOffsets) { termsHashPerField.InitReader(prox, termID, 1); } // TODO: really TermsHashPerField should take over most // of this loop, including merge sort of terms from // multiple threads and interacting with the // TermsConsumer, only calling out to us (passing us the // DocsConsumer) to handle delivery of docs/positions PostingsConsumer postingsConsumer = termsConsumer.StartTerm(text); int? delDocLimit; if (segDeletes != null) { protoTerm.Bytes = text; int? docIDUpto; segDeletes.TryGetValue(protoTerm, out docIDUpto); if (docIDUpto != null) { delDocLimit = docIDUpto; } else { delDocLimit = 0; } } else { delDocLimit = 0; } // Now termStates has numToMerge FieldMergeStates // which all share the same term. Now we must // interleave the docID streams. int docFreq = 0; long totalTermFreq = 0; int docID = 0; while (true) { //System.out.println(" cycle"); int termFreq; if (freq.Eof()) { if (postings.lastDocCodes[termID] != -1) { // Return last doc docID = postings.lastDocIDs[termID]; if (readTermFreq) { termFreq = postings.termFreqs[termID]; } else { termFreq = -1; } postings.lastDocCodes[termID] = -1; } else { // EOF break; } } else { int code = freq.ReadVInt32(); if (!readTermFreq) { docID += code; termFreq = -1; } else { docID += (int)((uint)code >> 1); if ((code & 1) != 0) { termFreq = 1; } else { termFreq = freq.ReadVInt32(); } } Debug.Assert(docID != postings.lastDocIDs[termID]); } docFreq++; Debug.Assert(docID < state.SegmentInfo.DocCount, "doc=" + docID + " maxDoc=" + state.SegmentInfo.DocCount); // NOTE: we could check here if the docID was // deleted, and skip it. However, this is somewhat // dangerous because it can yield non-deterministic // behavior since we may see the docID before we see // the term that caused it to be deleted. this // would mean some (but not all) of its postings may // make it into the index, which'd alter the docFreq // for those terms. We could fix this by doing two // passes, ie first sweep marks all del docs, and // 2nd sweep does the real flush, but I suspect // that'd add too much time to flush. visitedDocs.Set(docID); postingsConsumer.StartDoc(docID, writeTermFreq ? termFreq : -1); if (docID < delDocLimit) { // Mark it deleted. TODO: we could also skip // writing its postings; this would be // deterministic (just for this Term's docs). // TODO: can we do this reach-around in a cleaner way???? if (state.LiveDocs == null) { state.LiveDocs = docState.docWriter.codec.LiveDocsFormat.NewLiveDocs(state.SegmentInfo.DocCount); } if (state.LiveDocs.Get(docID)) { state.DelCountOnFlush++; state.LiveDocs.Clear(docID); } } totalTermFreq += termFreq; // Carefully copy over the prox + payload info, // changing the format to match Lucene's segment // format. if (readPositions || readOffsets) { // we did record positions (& maybe payload) and/or offsets int position = 0; int offset = 0; for (int j = 0; j < termFreq; j++) { BytesRef thisPayload; if (readPositions) { int code = prox.ReadVInt32(); position += (int)((uint)code >> 1); if ((code & 1) != 0) { // this position has a payload int payloadLength = prox.ReadVInt32(); if (payload == null) { payload = new BytesRef(); payload.Bytes = new byte[payloadLength]; } else if (payload.Bytes.Length < payloadLength) { payload.Grow(payloadLength); } prox.ReadBytes(payload.Bytes, 0, payloadLength); payload.Length = payloadLength; thisPayload = payload; } else { thisPayload = null; } if (readOffsets) { int startOffset = offset + prox.ReadVInt32(); int endOffset = startOffset + prox.ReadVInt32(); if (writePositions) { if (writeOffsets) { Debug.Assert(startOffset >= 0 && endOffset >= startOffset, "startOffset=" + startOffset + ",endOffset=" + endOffset + ",offset=" + offset); postingsConsumer.AddPosition(position, thisPayload, startOffset, endOffset); } else { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } offset = startOffset; } else if (writePositions) { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } } } postingsConsumer.FinishDoc(); } termsConsumer.FinishTerm(text, new TermStats(docFreq, writeTermFreq ? totalTermFreq : -1)); sumTotalTermFreq += totalTermFreq; sumDocFreq += docFreq; } termsConsumer.Finish(writeTermFreq ? sumTotalTermFreq : -1, sumDocFreq, visitedDocs.Cardinality()); } } }
using System; using System.Linq; using System.ComponentModel.DataAnnotations; using Csla; using System.ComponentModel; using System.Threading.Tasks; namespace ProjectTracker.Library { [Serializable()] public class ResourceEdit : CslaBaseTypes.BusinessBase<ResourceEdit> { public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp); [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public byte[] TimeStamp { get { return GetProperty(TimeStampProperty); } set { SetProperty(TimeStampProperty, value); } } public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id); public int Id { get { return GetProperty(IdProperty); } set { SetProperty(IdProperty, value); } } public static readonly PropertyInfo<string> LastNameProperty = RegisterProperty<string>(c => c.LastName); [Display(Name = "Last name")] [Required] [StringLength(50)] public string LastName { get { return GetProperty(LastNameProperty); } set { SetProperty(LastNameProperty, value); } } public static readonly PropertyInfo<string> FirstNameProperty = RegisterProperty<string>(c => c.FirstName); [Display(Name = "First name")] [Required] [StringLength(50)] public string FirstName { get { return GetProperty(FirstNameProperty); } set { SetProperty(FirstNameProperty, value); } } [Display(Name = "Full name")] public string FullName { get { return LastName + ", " + FirstName; } } public static readonly PropertyInfo<ResourceAssignments> AssignmentsProperty = RegisterProperty<ResourceAssignments>(c => c.Assignments); public ResourceAssignments Assignments { get { return LazyGetProperty(AssignmentsProperty, DataPortal.Create<ResourceAssignments>); } private set { LoadProperty(AssignmentsProperty, value); } } public override string ToString() { return Id.ToString(); } protected override void AddBusinessRules() { base.AddBusinessRules(); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, LastNameProperty, "ProjectManager")); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, FirstNameProperty, "ProjectManager")); BusinessRules.AddRule(new NoDuplicateProject { PrimaryProperty = AssignmentsProperty }); } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void AddObjectAuthorizationRules() { Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.CreateObject, "ProjectManager")); Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "ProjectManager")); Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, "ProjectManager", "Administrator")); } protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e) { if (e.ChildObject is ResourceAssignments) { BusinessRules.CheckRules(AssignmentsProperty); OnPropertyChanged(AssignmentsProperty); } base.OnChildChanged(e); } private class NoDuplicateProject : Csla.Rules.BusinessRule { protected override void Execute(Csla.Rules.RuleContext context) { var target = (ResourceEdit)context.Target; foreach (var item in target.Assignments) { var count = target.Assignments.Count(r => r.ProjectId == item.ProjectId); if (count > 1) { context.AddErrorResult("Duplicate projects not allowed"); return; } } } } public static async Task<ResourceEdit> NewResourceEditAsync() { return await DataPortal.CreateAsync<ResourceEdit>(); } public static async Task<ResourceEdit> GetResourceEditAsync(int id) { return await DataPortal.FetchAsync<ResourceEdit>(id); } public static async Task<bool> ExistsAsync(int id) { var cmd = new ResourceExistsCommand(id); cmd = await DataPortal.ExecuteAsync(cmd); return cmd.ResourceExists; } public static void NewResourceEdit(EventHandler<DataPortalResult<ResourceEdit>> callback) { DataPortal.BeginCreate<ResourceEdit>(callback); } public static void GetResourceEdit(int id, EventHandler<DataPortalResult<ResourceEdit>> callback) { DataPortal.BeginFetch<ResourceEdit>(id, callback); } #if FULL_DOTNET public static ResourceEdit NewResourceEdit() { return DataPortal.Create<ResourceEdit>(); } public static ResourceEdit GetResourceEdit(int id) { return DataPortal.Fetch<ResourceEdit>(id); } public static void DeleteResourceEdit(int id) { DataPortal.Delete<ResourceEdit>(id); } public static bool Exists(int id) { var cmd = new ResourceExistsCommand(id); cmd = DataPortal.Execute(cmd); return cmd.ResourceExists; } #endif [RunLocal] protected override void DataPortal_Create() { base.DataPortal_Create(); } #if FULL_DOTNET private void DataPortal_Fetch(int id) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); var data = dal.Fetch(id); using (BypassPropertyChecks) { Id = data.Id; FirstName = data.FirstName; LastName = data.LastName; TimeStamp = data.LastChanged; Assignments = DataPortal.FetchChild<ResourceAssignments>(id); } } } protected override void DataPortal_Insert() { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ResourceDto { FirstName = this.FirstName, LastName = this.LastName }; dal.Insert(item); Id = item.Id; TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this); } } protected override void DataPortal_Update() { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ResourceDto { Id = this.Id, FirstName = this.FirstName, LastName = this.LastName, LastChanged = this.TimeStamp }; dal.Update(item); TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this); } } protected override void DataPortal_DeleteSelf() { using (BypassPropertyChecks) DataPortal_Delete(this.Id); } private void DataPortal_Delete(int id) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { Assignments.Clear(); FieldManager.UpdateChildren(this); var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); dal.Delete(id); } } #endif } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; using ContentPatcher.Framework.ConfigModels; using Pathoschild.Stardew.Common.Utilities; using StardewModdingAPI; using StardewValley; using xTile; namespace ContentPatcher.Framework.Locations { /// <summary>Encapsulates loading custom location data and adding it to the game.</summary> [SuppressMessage("ReSharper", "CommentTypo", Justification = "'TMXL' is not a typo.")] [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "'TMXL' is not a typo.")] [SuppressMessage("ReSharper", "StringLiteralTypo", Justification = "'TMXL' is not a typo.")] internal class CustomLocationManager : IAssetLoader { /********* ** Fields *********/ /// <summary>A pattern which matches a valid location name.</summary> private static readonly Regex ValidNamePattern = new("^[a-z0-9_]+", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>The registered locations regardless of validity.</summary> private readonly List<CustomLocationData> CustomLocations = new(); /// <summary>The enabled locations indexed by their normalized map path.</summary> private readonly InvariantDictionary<CustomLocationData> CustomLocationsByMapPath = new(); /// <summary>Encapsulates monitoring and logging.</summary> private readonly IMonitor Monitor; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> public CustomLocationManager(IMonitor monitor) { this.Monitor = monitor; } /// <summary>Parse a raw custom location model, and validate that it's valid.</summary> /// <param name="config">The raw location config model.</param> /// <param name="contentPack">The content pack loading the file.</param> /// <param name="error">An error phrase indicating why parsing failed (if applicable).</param> public bool TryAddCustomLocationConfig(CustomLocationConfig config, IContentPack contentPack, out string error) { // validate config if (!this.TryParseCustomLocationConfig(config, contentPack, out CustomLocationData parsed, out error)) return false; this.CustomLocations.Add(parsed); if (parsed.IsEnabled) this.CustomLocationsByMapPath[parsed.PublicMapPath] = parsed; return true; } /// <summary>Enforce that custom location maps have a unique name.</summary> public void EnforceUniqueNames() { // get locations with duplicated names var duplicateLocations = ( from location in this.CustomLocations from name in new[] { location.Name }.Concat(location.MigrateLegacyNames) group location by name into locationGroup select new { Name = locationGroup.Key, Locations = locationGroup.ToArray() } ) .Where(group => group.Locations.Length > 1); // warn and disable duplicates foreach (var group in duplicateLocations.OrderByHuman(p => p.Name)) { // log error string[] contentPackNames = group.Locations.Select(p => p.ModName).OrderByHuman().Distinct().ToArray(); string error = contentPackNames.Length > 1 ? $"The '{group.Name}' location was added by multiple content packs ('{string.Join("', '", contentPackNames)}')." : $"The '{group.Name}' location was added multiple times in the '{contentPackNames[0]}' content pack."; error += " This location won't be added to the game."; this.Monitor.Log(error, LogLevel.Error); // disable locations foreach (var location in group.Locations) location.Disable(error); } // remove disabled locations foreach (var pair in this.CustomLocationsByMapPath.Where(p => !p.Value.IsEnabled).ToArray()) this.CustomLocationsByMapPath.Remove(pair.Key); } /// <summary>Add all locations to the game, if applicable.</summary> /// <param name="saveLocations">The locations in the save file being loaded, or <c>null</c> when creating a new save.</param> /// <param name="gameLocations">The locations that will be populated from the save data.</param> public void Apply(IList<GameLocation> saveLocations, IList<GameLocation> gameLocations) { // get valid locations CustomLocationData[] customLocations = this.CustomLocations.Where(p => p.IsEnabled).ToArray(); if (!customLocations.Any()) return; // migrate legacy locations List<MigratedLocation> migratedLocations = new List<MigratedLocation>(); if (saveLocations?.Any() == true) this.MigrateLegacyLocations(saveLocations, gameLocations, customLocations, migratedLocations); this.UpdateLocationReferences(SaveGame.loaded, migratedLocations); // log location list if (this.Monitor.IsVerbose) { var locationsByPack = customLocations .OrderByHuman(p => p.Name) .GroupBy(p => p.ModName) .OrderByHuman(p => p.Key); this.Monitor.VerboseLog($"Adding {customLocations.Length} locations:\n- {string.Join("\n- ", locationsByPack.Select(group => $"{group.Key}: {string.Join(", ", group.Select(p => p.Name))}"))}."); } // add locations foreach (CustomLocationData location in customLocations) { try { gameLocations.Add(new GameLocation(mapPath: location.PublicMapPath, name: location.Name)); } catch (Exception ex) { this.Monitor.Log($"{location.ContentPack.Manifest.Name} failed to load location '{location.Name}'. If you save after this point, any previous content in that location will be lost permanently.\nTechnical details: {ex}", LogLevel.Error); } } } /// <inheritdoc /> public bool CanLoad<T>(IAssetInfo asset) { return this.CustomLocationsByMapPath.ContainsKey(asset.AssetName); } /// <inheritdoc /> public T Load<T>(IAssetInfo asset) { // not a handled map if (!this.CustomLocationsByMapPath.TryGetValue(asset.AssetName, out CustomLocationData location)) throw new InvalidOperationException($"Unexpected asset name '{asset.AssetName}'."); // invalid type if (!typeof(Map).IsAssignableFrom(typeof(T))) throw new InvalidOperationException($"Unexpected attempt to load asset '{asset.AssetName}' as a {typeof(T)} asset instead of {typeof(Map)}."); // load asset return location.ContentPack.LoadAsset<T>(location.FromMapFile); } /// <summary>Get the defined custom locations.</summary> public IEnumerable<CustomLocationData> GetCustomLocationData() { return this.CustomLocations; } /********* ** Private methods *********/ /// <summary>Parse a raw custom location model, and validate that it's valid.</summary> /// <param name="config">The raw location config model.</param> /// <param name="contentPack">The content pack loading the file.</param> /// <param name="parsed">The parsed value.</param> /// <param name="error">An error phrase indicating why parsing failed (if applicable).</param> private bool TryParseCustomLocationConfig(CustomLocationConfig config, IContentPack contentPack, out CustomLocationData parsed, out string error) { static bool Fail(string reason, CustomLocationData parsed, out string setError) { setError = reason; parsed.Disable(reason); return false; } // read values string name = config?.Name?.Trim(); string fromMapFile = config?.FromMapFile?.Trim(); string[] migrateLegacyNames = config?.MigrateLegacyNames?.Select(p => p.Trim()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray() ?? Array.Empty<string>(); parsed = new CustomLocationData(name, fromMapFile, migrateLegacyNames, contentPack); // validate name if (string.IsNullOrWhiteSpace(name)) return Fail($"the {nameof(config.Name)} field is required.", parsed, out error); if (!CustomLocationManager.ValidNamePattern.IsMatch(name)) return Fail($"the {nameof(config.Name)} field can only contain alphanumeric or underscore characters.", parsed, out error); if (!name.StartsWith("Custom_")) return Fail($"the {nameof(config.Name)} field must be prefixed with 'Custom_' to avoid conflicting with current or future vanilla locations.", parsed, out error); // validate map file if (string.IsNullOrWhiteSpace(fromMapFile)) return Fail($"the {nameof(config.FromMapFile)} field is required.", parsed, out error); if (!contentPack.HasFile(fromMapFile)) return Fail($"the {nameof(config.FromMapFile)} field specifies a file '{fromMapFile}' which doesn't exist in the content pack.", parsed, out error); // create instance error = null; return true; } /// <summary>Update references to renamed locations, if needed.</summary> /// <param name="saveData">The save data to migrate.</param> /// <param name="migratedLocations">The location migrations, if any.</param> private void UpdateLocationReferences(SaveGame saveData, IList<MigratedLocation> migratedLocations) { if (!migratedLocations.Any()) return; var oldNameMap = migratedLocations.ToDictionary(p => p.OldName); foreach (GameLocation location in saveData.locations) { // update NPC home maps foreach (NPC npc in location.characters) { string curName = npc.DefaultMap; if (curName != null && oldNameMap.TryGetValue(curName, out MigratedLocation migration)) { string newName = migration.SaveLocation.Name; this.Monitor.Log($"'{migration.CustomLocation.ModName}' changed default map for NPC '{npc.Name}' from '{curName}' to '{newName}'.", LogLevel.Info); npc.DefaultMap = newName; } } } } /// <summary>Migrate locations which match <see cref="CustomLocationData.MigrateLegacyNames"/> to the new location name.</summary> /// <param name="saveLocations">The locations in the save file being loaded.</param> /// <param name="gameLocations">The locations that will be populated from the save data.</param> /// <param name="customLocations">The custom location data.</param> /// <param name="migratedLocations">A list to update with location migrations, if any.</param> private void MigrateLegacyLocations(IList<GameLocation> saveLocations, IList<GameLocation> gameLocations, CustomLocationData[] customLocations, IList<MigratedLocation> migratedLocations) { // get location lookups Lazy<IDictionary<string, GameLocation>> saveLocationsByName = new(() => this.MapByName(saveLocations)); Lazy<IDictionary<string, GameLocation>> gameLocationsByName = new(() => this.MapByName(gameLocations)); var tmxl = new TmxlLocationLoader(this.Monitor); // migrate locations if needed foreach (CustomLocationData customLocation in customLocations.Where(p => p.HasLegacyNames)) { this.MigrateLegacyLocation( customLocation: customLocation, saveLocations: saveLocations, saveLocationsByName: saveLocationsByName, gameLocationsByName: gameLocationsByName, tmxl: tmxl, migratedLocations: migratedLocations ); } } /// <summary>Migrate legacy locations in the save file for the given custom location, if needed.</summary> /// <param name="customLocation">The custom location for which to migrate save data.</param> /// <param name="saveLocations">The locations in the save file being loaded.</param> /// <param name="saveLocationsByName">The <paramref name="saveLocations"/> indexed by name.</param> /// <param name="gameLocationsByName">The locations that will be populated from the save data, indexed by name.</param> /// <param name="tmxl">The locations in TMXL Map Toolkit's serialized data.</param> /// <param name="migratedLocations">A list to update with location migrations, if any.</param> /// <returns>Returns whether any save data was migrated.</returns> [SuppressMessage("SMAPI.CommonErrors", "AvoidNetField", Justification = "This is deliberate due to the Name property being readonly.")] private void MigrateLegacyLocation(CustomLocationData customLocation, IList<GameLocation> saveLocations, Lazy<IDictionary<string, GameLocation>> saveLocationsByName, Lazy<IDictionary<string, GameLocation>> gameLocationsByName, TmxlLocationLoader tmxl, IList<MigratedLocation> migratedLocations) { if (!customLocation.HasLegacyNames) return; // ignore names which match an existing in-game location, since that would cause data loss var legacyNames = new List<string>(); foreach (string legacyName in customLocation.MigrateLegacyNames) { if (gameLocationsByName.Value.ContainsKey(legacyName)) this.Monitor.Log($"'{customLocation.ModName}' defines a legacy location name '{legacyName}' which matches a non-Content Patcher location and will be ignored.", LogLevel.Warn); else legacyNames.Add(legacyName); } // already in save file if (saveLocationsByName.Value.ContainsKey(customLocation.Name)) return; // migrate from old name foreach (string legacyName in legacyNames) { if (!saveLocationsByName.Value.TryGetValue(legacyName, out GameLocation saveLocation)) continue; this.Monitor.Log($"'{customLocation.ModName}' renamed saved location '{legacyName}' to '{customLocation.Name}'.", LogLevel.Info); saveLocation.name.Value = customLocation.Name; saveLocationsByName.Value.Remove(legacyName); saveLocationsByName.Value[saveLocation.Name] = saveLocation; migratedLocations.Add( new MigratedLocation(legacyName, saveLocation, customLocation) ); return; } // migrate from TMXL Map Toolkit foreach (string legacyName in legacyNames) { if (!tmxl.TryGetLocation(legacyName, out GameLocation tmxlLocation)) continue; this.Monitor.Log($"'{customLocation.ModName}' migrated saved TMXL Map Toolkit location '{legacyName}' to Content Patcher location '{customLocation.Name}'.", LogLevel.Info); saveLocations.Add(tmxlLocation); tmxlLocation.name.Value = customLocation.Name; saveLocationsByName.Value[customLocation.Name] = tmxlLocation; migratedLocations.Add( new MigratedLocation(legacyName, tmxlLocation, customLocation) ); return; } } /// <summary>Get a location-by-name lookup.</summary> /// <param name="locations">The locations for which to build a lookup.</param> private IDictionary<string, GameLocation> MapByName(IEnumerable<GameLocation> locations) { var lookup = new Dictionary<string, GameLocation>(); foreach (GameLocation location in locations) lookup[location.NameOrUniqueName] = location; return lookup; } } }
using Aardvark.Base; using System; using System.Collections; using System.Collections.Generic; namespace Aardvark.Base.Coder { /// <summary> /// This associates a type with a reading function and a writing /// action for the type. /// </summary> public struct TypeReaderAndWriter { public readonly Type Type; public readonly Func<IReadingCoder, object> Reader; public readonly Action<IWritingCoder, object> Writer; public TypeReaderAndWriter(Type type, Func<IReadingCoder, object> reader, Action<IWritingCoder, object> writer ) { Type = type; Reader = reader; Writer = writer; } } /// <summary> /// This class provides coding of primitive types. Reading and Witing of /// additional primitive types can be registered via the static /// <see cref="Add"/> methods. /// </summary> public static partial class TypeCoder { static Dictionary<Type, Action<IWritingCoder, Type, object>> s_genericWriterMap = new Dictionary<Type, Action<IWritingCoder, Type, object>> { { typeof(List<>), (c,t,o) => { var v = (IList)o; c.Code(t, ref v); } }, { typeof(Dictionary<,>),(c,t,o) => { var v = (IDictionary)o; c.Code(t, ref v); } }, { typeof(Dict<,>), (c,t,o) => { var v = (ICountableDict)o; c.Code(t, ref v); } }, { typeof(IntDict<>), (c,t,o) => { var v = (ICountableDict)o; c.Code(t, ref v); } }, { typeof(SymbolDict<>), (c,t,o) => { var v = (ICountableDict)o; c.Code(t, ref v); } }, { typeof(DictSet<>), (c,t,o) => { var v = (ICountableDictSet)o; c.Code(t, ref v); } }, { typeof(Vector<>), (c,t,o) => { var v = (IArrayVector)o; c.Code(t, ref v); } }, { typeof(Matrix<>), (c,t,o) => { var v = (IArrayMatrix)o; c.Code(t, ref v); } }, { typeof(Volume<>), (c,t,o) => { var v = (IArrayVolume)o; c.Code(t, ref v); } }, { typeof(Tensor<>), (c,t,o) => { var v = (IArrayTensorN)o; c.Code(t, ref v); } }, { typeof(HashSet<>), (c,t,o) => { c.CodeHashSet(t, ref o); } }, }; static Dictionary<Type, Func<IReadingCoder, Type, object>> s_genericReaderMap = new Dictionary<Type, Func<IReadingCoder, Type, object>> { { typeof(List<>), (c,t) => { var v = default(IList); c.Code(t, ref v); return v; } }, { typeof(Dictionary<,>),(c,t) => { var v = default(IDictionary); c.Code(t, ref v); return v; } }, { typeof(Dict<,>), (c,t) => { var v = default(ICountableDict); c.Code(t, ref v); return v; } }, { typeof(IntDict<>), (c,t) => { var v = default(ICountableDict); c.Code(t, ref v); return v; } }, { typeof(SymbolDict<>), (c,t) => { var v = default(ICountableDict); c.Code(t, ref v); return v; } }, { typeof(DictSet<>), (c,t) => { var v = default(ICountableDictSet); c.Code(t, ref v); return v; } }, { typeof(Vector<>), (c,t) => { var v = default(IArrayVector); c.Code(t, ref v); return v; } }, { typeof(Matrix<>), (c,t) => { var v = default(IArrayMatrix); c.Code(t, ref v); return v; } }, { typeof(Volume<>), (c,t) => { var v = default(IArrayVolume); c.Code(t, ref v); return v; } }, { typeof(Tensor<>), (c,t) => { var v = default(IArrayTensorN); c.Code(t, ref v); return v; } }, { typeof(HashSet<>), (c,t) => { object o = null; c.CodeHashSet(t, ref o); return o; } }, }; public static bool WritePrimitive(IWritingCoder coder, Type type, ref object obj) { Action<IWritingCoder, object> writer; if (TypeWriterMap.TryGetValue(type, out writer)) { writer(coder, obj); return true; } else if (type.IsEnum) { coder.CodeEnum(type, ref obj); return true; } else if (type.IsArray) { Array a = (Array)obj; coder.Code(type, ref a); return true; } else if (type.IsGenericType) { Action<IWritingCoder, Type, object> genericWriter; if (s_genericWriterMap.TryGetValue( type.GetGenericTypeDefinition(), out genericWriter)) { genericWriter(coder, type, obj); return true; } } return false; } /// <summary> /// Write an object based on the supplied type. /// </summary> public static void Write(IWritingCoder coder, Type type, ref object obj) { if (!WritePrimitive(coder, type, ref obj)) coder.Code(ref obj); } /// <summary> /// Read an object based on the supplied type. /// </summary> public static bool ReadPrimitive(IReadingCoder coder, Type type, ref object obj) { Func<IReadingCoder, object> reader; if (TypeReaderMap.TryGetValue(type, out reader)) { obj = reader(coder); return true; } else if (type.IsEnum) { coder.CodeEnum(type, ref obj); return true; } else if (type.IsArray) { Array a = null; coder.Code(type, ref a); obj = a; return true; } else if (type.IsGenericType) { Func<IReadingCoder, Type, object> genericReader; Type genericType = type.GetGenericTypeDefinition(); if (s_genericReaderMap.TryGetValue(genericType, out genericReader)) { obj = genericReader(coder, type); return true; } } return false; } /// <summary> /// Read an object based on the supplied type. /// </summary> public static void Read(IReadingCoder coder, Type type, ref object obj) { if (!ReadPrimitive(coder, type, ref obj)) coder.Code(ref obj); } public static bool IsDirectlyCodeable(Type type) { if (TypeWriterMap.ContainsKey(type)) return true; if (type.IsEnum) return true; if (type.IsArray) return true; if (type.IsGenericType) { Type genericType = type.GetGenericTypeDefinition(); if (s_genericWriterMap.ContainsKey(genericType)) return true; } return false; } /// <summary> /// Register an array of additional read functions and write /// procedures for the data types. /// </summary> public static void Add(IEnumerable<TypeReaderAndWriter> typeReaderAndWriters) { foreach (var trw in typeReaderAndWriters) { TypeReaderMap[trw.Type] = trw.Reader; TypeWriterMap[trw.Type] = trw.Writer; } } /// <summary> /// Marker class signifying coding of null pointers. /// </summary> public static class Null { } /// <summary> /// Marker class signifying coding of references. /// </summary> public static class Reference { } public static partial class Default { private static bool s_initialized = false; public static void Init() { if (s_initialized) return; s_initialized = true; TypeInfo.Add(TypeCoder.Default.Reference); TypeInfo.Add(TypeCoder.Default.Null); TypeInfo.Add(TypeCoder.Default.Basic); } /// <summary> /// The default way of encoding null pointers. /// </summary> public static TypeInfo[] Null = new[] { new TypeInfo("null", typeof(TypeCoder.Null), TypeInfo.Option.Active), }; public static TypeInfo[] Reference = new[] { new TypeInfo("ref", typeof(TypeCoder.Reference), TypeInfo.Option.Active), }; public static TypeInfo[] NoNull = new[] { new TypeInfo("null", typeof(TypeCoder.Null)), }; public static TypeInfo[] NoReference = new[] { new TypeInfo("ref", typeof(TypeCoder.Reference)), }; } } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using CommonTests.Framework; using NUnit.Framework; using System.Threading.Tasks; namespace CommonTests.IntegrationTests.DynamoDB { public partial class DynamoDBTests : TestBase<AmazonDynamoDBClient> { [Test] [Category("DynamoDB")] public void TestTableCalls() { RunAsSync(async () => { // Only run these tests if we are not reusing tables if (ReuseTables) return; #pragma warning disable 162 await TestTableCallsAsync(); #pragma warning restore 162 }); } private async Task TestTableCallsAsync() { var tables = GetTableNames(); int tableCount = tables.Count; // Create hash-key table var table1Name = TableNamePrefix + "Table1"; await Client.CreateTableAsync( table1Name, new List<KeySchemaElement> { new KeySchemaElement { KeyType = KeyType.HASH, AttributeName = "Id" } }, new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.N } }, new ProvisionedThroughput { ReadCapacityUnits = DefaultReadCapacity, WriteCapacityUnits = DefaultWriteCapacity }); CreatedTables.Add(table1Name); // Create hash-and-range-key table var table2Name = TableNamePrefix + "Table2"; await Client.CreateTableAsync( table2Name, new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = "Name", KeyType = KeyType.RANGE } }, new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.N }, new AttributeDefinition { AttributeName = "Name", AttributeType = ScalarAttributeType.S } }, new ProvisionedThroughput { ReadCapacityUnits = DefaultReadCapacity, WriteCapacityUnits = DefaultWriteCapacity }); CreatedTables.Add(table2Name); // Create hash-key table with global index var table3Name = TableNamePrefix + "Table3"; await Client.CreateTableAsync(new CreateTableRequest { TableName = table3Name, AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.N }, new AttributeDefinition { AttributeName = "Company", AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = "Price", AttributeType = ScalarAttributeType.N } }, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { KeyType = KeyType.HASH, AttributeName = "Id" } }, GlobalSecondaryIndexes = new List<GlobalSecondaryIndex> { new GlobalSecondaryIndex { IndexName = "GlobalIndex", KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Company", KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = "Price", KeyType = KeyType.RANGE } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 1, WriteCapacityUnits = 1 }, Projection = new Projection { ProjectionType = ProjectionType.ALL } } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = DefaultReadCapacity, WriteCapacityUnits = DefaultWriteCapacity }, }); CreatedTables.Add(table3Name); // Wait for tables to be ready before creating another table with an index WaitForTableStatus(Client, CreatedTables, TableStatus.ACTIVE); // Create hash-and-range-key table with local and global indexes var table4Name = TableNamePrefix + "Table4"; await Client.CreateTableAsync(new CreateTableRequest { TableName = table4Name, AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.N }, new AttributeDefinition { AttributeName = "Name", AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = "Company", AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = "Price", AttributeType = ScalarAttributeType.N }, new AttributeDefinition { AttributeName = "Manager", AttributeType = ScalarAttributeType.S } }, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = "Name", KeyType = KeyType.RANGE } }, GlobalSecondaryIndexes = new List<GlobalSecondaryIndex> { new GlobalSecondaryIndex { IndexName = "GlobalIndex", KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Company", KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = "Price", KeyType = KeyType.RANGE } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 1, WriteCapacityUnits = 1 }, Projection = new Projection { ProjectionType = ProjectionType.ALL } } }, LocalSecondaryIndexes = new List<LocalSecondaryIndex> { new LocalSecondaryIndex { IndexName = "LocalIndex", KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = "Manager", KeyType = KeyType.RANGE } }, Projection = new Projection { ProjectionType = ProjectionType.INCLUDE, NonKeyAttributes = new List<string> { "Company", "Price" } } } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = DefaultReadCapacity, WriteCapacityUnits = DefaultWriteCapacity }, }); CreatedTables.Add(table4Name); tables = GetTableNames(); Assert.AreEqual(tableCount + 4, tables.Count); // Wait for tables to be ready WaitForTableStatus(Client, CreatedTables, TableStatus.ACTIVE); // Update throughput for a table await Client.UpdateTableAsync( table2Name, new ProvisionedThroughput { ReadCapacityUnits = DefaultReadCapacity * 2, WriteCapacityUnits = DefaultWriteCapacity * 2 }); // Wait for tables to be ready WaitForTableStatus(Client, CreatedTables, TableStatus.ACTIVE); // Delete new tables await Client.DeleteTableAsync(table1Name); await Client.DeleteTableAsync(table2Name); await Client.DeleteTableAsync(table3Name); await Client.DeleteTableAsync(table4Name); // Wait for tables to be deleted WaitForTableStatus(Client, new string[] { table1Name, table2Name, table3Name, table4Name }, null); // Count tables again tables = GetTableNames(); Assert.AreEqual(tableCount, tables.Count); CreatedTables.Remove(table1Name); CreatedTables.Remove(table2Name); CreatedTables.Remove(table3Name); CreatedTables.Remove(table4Name); } [Test] public void TestDataCalls() { RunAsSync(async () => { // Test hash-key table await TestHashTable(hashTableName); // Test hash-and-range-key table await TestHashRangeTable(hashRangeTableName); // Test batch gets and writes await TestBatchWriteGet(hashTableName, hashRangeTableName); // Test large batch gets and writes await TestLargeBatches(hashTableName); }); } private async Task TestHashTable(string hashTableName) { // Put item var nonEmptyListAV = new AttributeValue(); nonEmptyListAV.L = new List<AttributeValue> { new AttributeValue { S = "Data" }, new AttributeValue { N = "12" } }; // optional call to IsLSet = true, no-op nonEmptyListAV.IsLSet = true; Assert.AreEqual(2, nonEmptyListAV.L.Count); var emptyListAV = new AttributeValue(); emptyListAV.L = null; // call to IsLSet = true sets L to empty list emptyListAV.IsLSet = true; Assert.AreEqual(0, emptyListAV.L.Count); emptyListAV.L = new List<AttributeValue>(); // call to IsLSet = true sets L to empty list emptyListAV.IsLSet = true; Assert.AreEqual(0, emptyListAV.L.Count); var boolAV = new AttributeValue(); Assert.IsFalse(boolAV.IsBOOLSet); boolAV.BOOL = false; Assert.IsTrue(boolAV.IsBOOLSet); await Client.PutItemAsync(hashTableName, new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "1" } }, { "Product", new AttributeValue { S = "CloudSpotter" } }, { "Company", new AttributeValue { S = "CloudsAreGrate" } }, { "Tags", new AttributeValue { SS = new List<string> { "Prod", "1.0" } } }, { "Seller", new AttributeValue { S = "Big River" } }, { "Price", new AttributeValue { N = "900" } }, { "Null", new AttributeValue { NULL = true } }, { "EmptyList", emptyListAV }, { "NonEmptyList", nonEmptyListAV }, { "EmptyMap", new AttributeValue { IsMSet = true } }, { "BoolFalse", boolAV } }); // Get item var key1 = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "1" } } }; var item = (await Client.GetItemAsync(hashTableName, key1)).Item; // Verify empty collections and value type Assert.IsTrue(item["EmptyList"].IsLSet); Assert.IsFalse(item["EmptyList"].IsMSet); Assert.IsTrue(item["EmptyMap"].IsMSet); Assert.IsFalse(item["EmptyMap"].IsLSet); Assert.IsTrue(item["BoolFalse"].IsBOOLSet); Assert.IsFalse(item["BoolFalse"].BOOL); Assert.IsTrue(item["NonEmptyList"].IsLSet); Assert.AreEqual(nonEmptyListAV.L.Count, item["NonEmptyList"].L.Count); // Get nonexistent item var key2 = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "999" } } }; var getItemResult = await Client.GetItemAsync(hashTableName, key2); Assert.IsFalse(getItemResult.IsItemSet); // Get empty item getItemResult = await Client.GetItemAsync(new GetItemRequest { TableName = hashTableName, Key = key1, ProjectionExpression = "Coffee" }); Assert.IsTrue(getItemResult.IsItemSet); Assert.AreEqual(0, getItemResult.Item.Count); // Update item await Client.UpdateItemAsync(hashTableName, key1, new Dictionary<string, AttributeValueUpdate> { { "Product", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { S = "CloudSpotter 2.0" } } }, { "Seller", new AttributeValueUpdate { Action = AttributeAction.DELETE } }, { "Tags", new AttributeValueUpdate { Action = AttributeAction.ADD, Value = new AttributeValue { SS = new List<string> { "2.0" } } } } }); // Get updated item item = (await Client.GetItemAsync(hashTableName, key1)).Item; Assert.IsTrue(item["Product"].S.IndexOf("2.0") >= 0); Assert.AreEqual(3, item["Tags"].SS.Count); Assert.IsFalse(item.ContainsKey("Seller")); // Scan all items var scanConditions = new Dictionary<string, Condition> { { "Company", new Condition { ComparisonOperator = ComparisonOperator.GE, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Cloud" } } } } }; var items = await Scan(hashTableName, scanConditions); Assert.AreEqual(1, items.Count); // Update non-existent item key2 = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "2" } } }; await Client.UpdateItemAsync(hashTableName, key2, new Dictionary<string, AttributeValueUpdate> { { "Product", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { S = "CloudDebugger" } } }, { "Company", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { S = "CloudsAreGrate" } } }, { "Tags", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { SS = new List<string> { "Test" } } } }, { "Price", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { N = "42" } } } }); // Get updated item item = (await Client.GetItemAsync(hashTableName, key2)).Item; Assert.IsTrue(item["Product"].S.IndexOf("Debugger") >= 0); Assert.AreEqual(1, item["Tags"].SS.Count); Assert.IsFalse(item.ContainsKey("Seller")); // Scan all items items = await Scan(hashTableName, scanConditions); Assert.AreEqual(2, items.Count); // Query global index items = (await Client.QueryAsync(new QueryRequest { TableName = hashTableName, IndexName = "GlobalIndex", KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Company", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "CloudsAreGrate" } } } }, // Second Query condition must be RangeKey [Conditon] [Value] { "Price", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "50" } } } } } })).Items; Assert.AreEqual(1, items.Count); // Scan global index items = (await Client.ScanAsync(new ScanRequest { TableName = hashTableName, IndexName = "GlobalIndex", ScanFilter = new Dictionary<string, Condition> { // First condition will be HashKey EQ [Value] { "Company", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "CloudsAreGrate" } } } }, // Second condition will be RangeKey [Conditon] [Value] { "Price", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "50" } } } } } })).Items; Assert.AreEqual(1, items.Count); } private async Task TestHashRangeTable(string hashRangeTableName) { // Put items await Client.PutItemAsync(hashRangeTableName, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Alan" } }, { "Age", new AttributeValue { N = "31" } }, { "Company", new AttributeValue { S = "Big River" } }, { "Score", new AttributeValue { N = "120" } }, { "Manager", new AttributeValue { S = "Barbara"} } }); await Client.PutItemAsync(hashRangeTableName, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Chuck" } }, { "Age", new AttributeValue { N = "30" } }, { "Company", new AttributeValue { S = "Big River" } }, { "Score", new AttributeValue { N = "94" } }, { "Manager", new AttributeValue { S = "Barbara"} } }); await Client.PutItemAsync(hashRangeTableName, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Diane" } }, { "Age", new AttributeValue { N = "40" } }, { "Company", new AttributeValue { S = "Madeira" } }, { "Score", new AttributeValue { N = "140" } }, { "Manager", new AttributeValue { S = "Eva"} } }); await Client.PutItemAsync(hashRangeTableName, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Diane" } }, { "Age", new AttributeValue { N = "24" } }, { "Company", new AttributeValue { S = "Madeira" } }, { "Score", new AttributeValue { N = "101" } }, { "Manager", new AttributeValue { S = "Francis"} } }); // Scan all items var scanConditions = new Dictionary<string, Condition> { { "Company", new Condition { ComparisonOperator = ComparisonOperator.GE, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Big" } } } } }; var items = await Scan(hashRangeTableName, scanConditions); Assert.AreEqual(4, items.Count); // Scan in parallel items = await ParallelScan(hashRangeTableName, segments: 2, conditions: scanConditions); Assert.AreEqual(4, items.Count); // Query table with no range-key condition items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, } })).Items; Assert.AreEqual(2, items.Count); // Query table with no range-key condition and no returned attributes items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, }, ProjectionExpression = "Coffee" })).Items; Assert.AreEqual(2, items.Count); Assert.AreEqual(0, items[0].Count); Assert.AreEqual(0, items[1].Count); // Query table with hash-key condition expression items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, KeyConditionExpression = "#H = :val", ExpressionAttributeNames = new Dictionary<string, string> { { "#H", "Name"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":val", new AttributeValue { S = "Diane" } } } })).Items; Assert.AreEqual(2, items.Count); // Query table with key condition expression items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, KeyConditionExpression = "#H = :name and #R > :age", ExpressionAttributeNames = new Dictionary<string, string> { { "#H", "Name" }, { "#R", "Age" } }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":name", new AttributeValue { S = "Diane" } }, { ":age", new AttributeValue { N = "30" } } } })).Items; Assert.AreEqual(1, items.Count); // Query global index items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, IndexName = "GlobalIndex", KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Company", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Big River" } } } }, // Second Query condition must be RangeKey [Conditon] [Value] { "Score", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "100" } } } } } })).Items; Assert.AreEqual(1, items.Count); // Query local index with no range-key condition items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, } })).Items; Assert.AreEqual(2, items.Count); // Query local index with range-key condition items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, // Second Query condition must be RangeKey [Conditon] [Value] { "Manager", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Francis" } } } } } })).Items; // Query local index with a query filter items = (await Client.QueryAsync(new QueryRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", KeyConditions = new Dictionary<string, Condition> { // First Query condition must be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } } }, QueryFilter = new Dictionary<string, Condition> { // QueryFilter conditions must be non-key attributes { "Score", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "120" } } } } } })).Items; Assert.AreEqual(1, items.Count); // Scan global index items = (await Client.ScanAsync(new ScanRequest { TableName = hashRangeTableName, IndexName = "GlobalIndex", ScanFilter = new Dictionary<string, Condition> { // First condition will be HashKey EQ [Value] { "Company", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Big River" } } } }, // Second condition will be RangeKey [Conditon] [Value] { "Score", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "100" } } } } } })).Items; Assert.AreEqual(1, items.Count); // Scan local index with no range-key condition items = (await Client.ScanAsync(new ScanRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", ScanFilter = new Dictionary<string, Condition> { // First condition will be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, } })).Items; Assert.AreEqual(2, items.Count); // Scan local index with range-key condition items = (await Client.ScanAsync(new ScanRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", ScanFilter = new Dictionary<string, Condition> { // First condition will be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, // Second condition will be RangeKey [Conditon] [Value] { "Manager", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Francis" } } } } } })).Items; // Scan local index with a non-key condition items = (await Client.ScanAsync(new ScanRequest { TableName = hashRangeTableName, IndexName = "LocalIndex", ScanFilter = new Dictionary<string, Condition> { // First condition will be HashKey EQ [Value] { "Name", new Condition { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "Diane" } } } }, // Non-key attributes condition { "Score", new Condition { ComparisonOperator = ComparisonOperator.GT, AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "120" } } } } } })).Items; Assert.AreEqual(1, items.Count); } private async Task TestBatchWriteGet(string hashTableName, string hashRangeTableName) { // Put 1 item and delete 2 items across 2 tables await Client.BatchWriteItemAsync(new Dictionary<string, List<WriteRequest>> { { hashTableName, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string,AttributeValue> { { "Id", new AttributeValue { N = "6" } }, { "Product", new AttributeValue { S = "CloudVerifier" } }, { "Company", new AttributeValue { S = "CloudsAreGrate" } }, } } }, new WriteRequest { DeleteRequest = new DeleteRequest { Key = new Dictionary<string,AttributeValue> { { "Id", new AttributeValue { N = "2" } } } } } } }, { hashRangeTableName, new List<WriteRequest> { new WriteRequest { DeleteRequest = new DeleteRequest { Key = new Dictionary<string,AttributeValue> { { "Name", new AttributeValue { S = "Diane" } }, { "Age", new AttributeValue { N = "24" } }, } } } } } }); // Get 5 items across 2 tables var batchGetResult = await Client.BatchGetItemAsync(new Dictionary<string, KeysAndAttributes> { { hashTableName, new KeysAndAttributes { Keys = new List<Dictionary<string,AttributeValue>> { new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "1" } } }, new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "6" } } } } } }, { hashRangeTableName, new KeysAndAttributes { Keys = new List<Dictionary<string,AttributeValue>> { new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Alan" } }, { "Age", new AttributeValue { N = "31" } } }, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Chuck" } }, { "Age", new AttributeValue { N = "30" } } }, new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "Diane" } }, { "Age", new AttributeValue { N = "40" } } } } } } }); var tableItems = batchGetResult.Responses; var hashItems = tableItems[hashTableName]; var hashRangeItems = tableItems[hashRangeTableName]; Assert.AreEqual(2, hashItems.Count); Assert.AreEqual(3, hashRangeItems.Count); } private async Task TestLargeBatches(string hashTableName) { int itemSize = 60 * 1024; Assert.IsTrue(itemSize < MaxItemSize); int itemCount = 25; // DynamoDB allows 1MB of data per operation, so itemSize * writeBatchSize < 1MB int writeBatchSize = (int)Math.Floor((decimal)OneMB / (decimal)itemSize); // Write large items to table in small batches List<string> itemIds = new List<string>(); for (int i = 0; i < itemCount; i += writeBatchSize) { var writtenIds = await WriteBigBatch(hashTableName, writeBatchSize, i, itemSize); itemIds.AddRange(writtenIds); } // Get large items from table in 1MB batches for (int i = 0; i < itemCount; i += MaxBatchSize) { List<string> itemsToGet = itemIds.GetRange(i, MaxBatchSize); if (itemsToGet.Count > 0) { int itemsRetrieved = await GetBigBatch(hashTableName, itemsToGet); Assert.AreEqual(itemsRetrieved, itemsToGet.Count); } } } private async Task<List<string>> WriteBigBatch(string hashTableName, int items, int itemsStartingIndex, int itemSize) { List<string> itemIds = new List<string>(); string itemData = new string('@', itemSize); List<WriteRequest> writeRequests = new List<WriteRequest>(); for (int i = 0; i < items; i++) { var itemId = (itemsStartingIndex + i).ToString(); itemIds.Add(itemId); var writeRequest = new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = itemId } }, { "Data", new AttributeValue { S = itemData }} } } }; writeRequests.Add(writeRequest); } var request = new BatchWriteItemRequest { RequestItems = new Dictionary<string, List<WriteRequest>> { { hashTableName, writeRequests } } }; BatchWriteItemResponse result; do { result = await Client.BatchWriteItemAsync(request); request.RequestItems = result.UnprocessedItems; } while (result.UnprocessedItems != null && result.UnprocessedItems.Count > 0); return itemIds; } private async Task<int> GetBigBatch(string hashTableName, List<string> idsToGet) { var keys = new List<Dictionary<string, AttributeValue>>(); foreach (var id in idsToGet) { keys.Add(new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = id } } }); } var request = new BatchGetItemRequest { RequestItems = new Dictionary<string, KeysAndAttributes> { { hashTableName, new KeysAndAttributes { Keys = keys } } } }; BatchGetItemResponse result; int itemsRetrieved = 0; do { result = await Client.BatchGetItemAsync(request); itemsRetrieved += result.Responses[hashTableName].Count; request.RequestItems = result.UnprocessedKeys; } while (result.UnprocessedKeys != null && result.UnprocessedKeys.Count > 0); return itemsRetrieved; } private List<string> GetTableNames() { return GetTableNamesHelper().ToList(); } private IEnumerable<string> GetTableNamesHelper() { var request = new ListTablesRequest(); ListTablesResponse response; do { response = Client.ListTablesAsync(request).Result; foreach (var tableName in response.TableNames) yield return tableName; request.ExclusiveStartTableName = response.LastEvaluatedTableName; } while (!string.IsNullOrEmpty(response.LastEvaluatedTableName)); } private async Task<List<Dictionary<string, AttributeValue>>> Scan(string tableName, Dictionary<string, Condition> conditions) { return await ScanHelper(tableName, conditions); } private async Task<List<Dictionary<string, AttributeValue>>> ParallelScan(string tableName, int segments, Dictionary<string, Condition> conditions) { var allItems = new List<Dictionary<string, AttributeValue>>(); for (int i = 0; i < segments; i++) { var segmentResults = await ScanHelper(tableName, conditions, i, segments); allItems.AddRange(segmentResults); } return allItems; } private async Task<List<Dictionary<string, AttributeValue>>> ScanHelper(string tableName, Dictionary<string, Condition> conditions, int? segment = null, int? totalSegments = null) { var items = new List<Dictionary<string, AttributeValue>>(); var request = new ScanRequest { TableName = tableName, ScanFilter = conditions, Limit = ScanLimit, }; if (segment.HasValue && totalSegments.HasValue) { request.Segment = segment.Value; request.TotalSegments = totalSegments.Value; } ScanResponse result; do { result = await Client.ScanAsync(request); foreach (var item in result.Items) items.Add(item); request.ExclusiveStartKey = result.LastEvaluatedKey; } while (result.LastEvaluatedKey != null && result.LastEvaluatedKey.Count > 0); return items; } } }
// 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.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.VisualTree; using Xunit; using System.Collections.ObjectModel; using Avalonia.UnitTests; namespace Avalonia.Controls.UnitTests { public class ItemsControlTests { [Fact] public void Should_Use_ItemTemplate_To_Create_Control() { var target = new ItemsControl { Template = GetTemplate(), ItemTemplate = new FuncDataTemplate<string>(_ => new Canvas()), }; target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; container.UpdateChild(); Assert.IsType<Canvas>(container.Child); } [Fact] public void Panel_Should_Have_TemplatedParent_Set_To_ItemsControl() { var target = new ItemsControl(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(target, target.Presenter.Panel.TemplatedParent); } [Fact] public void Container_Should_Have_TemplatedParent_Set_To_Null() { var target = new ItemsControl(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; Assert.Null(container.TemplatedParent); } [Fact] public void Container_Child_Should_Have_LogicalParent_Set_To_Container() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var root = new Window(); var target = new ItemsControl(); root.Content = target; var templatedParent = new Button(); target.TemplatedParent = templatedParent; target.Template = GetTemplate(); target.Items = new[] { "Foo" }; root.ApplyTemplate(); target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; Assert.Equal(container, container.Child.Parent); } } [Fact] public void Control_Item_Should_Be_Logical_Child_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Control_Item_Should_Be_Removed_From_Logical_Children_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); var items = new AvaloniaList<Control>(child); target.Template = GetTemplate(); target.Items = items; items.RemoveAt(0); Assert.Null(child.Parent); Assert.Null(child.GetLogicalParent()); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Clearing_Items_Should_Clear_Child_Controls_Parent_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; target.Items = null; Assert.Null(child.Parent); Assert.Null(((ILogical)child).LogicalParent); } [Fact] public void Clearing_Items_Should_Clear_Child_Controls_Parent() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); target.Items = null; Assert.Null(child.Parent); Assert.Null(((ILogical)child).LogicalParent); } [Fact] public void Adding_Control_Item_Should_Make_Control_Appear_In_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; // Should appear both before and after applying template. Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren()); target.ApplyTemplate(); Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren()); } [Fact] public void Adding_String_Item_Should_Make_TextBlock_Appear_In_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var logical = (ILogical)target; Assert.Equal(1, logical.LogicalChildren.Count); Assert.IsType<TextBlock>(logical.LogicalChildren[0]); } [Fact] public void Setting_Items_To_Null_Should_Remove_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.NotEmpty(target.GetLogicalChildren()); target.Items = null; Assert.Equal(new ILogical[0], target.GetLogicalChildren()); } [Fact] public void Setting_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; target.Items = new[] { child }; Assert.True(called); } [Fact] public void Setting_Items_To_Null_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Remove; target.Items = null; Assert.True(called); } [Fact] public void Changing_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Items = new[] { "Foo" }; Assert.True(called); } [Fact] public void Adding_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var items = new AvaloniaList<string> { "Foo" }; var called = false; target.Template = GetTemplate(); target.Items = items; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; items.Add("Bar"); Assert.True(called); } [Fact] public void Removing_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var items = new AvaloniaList<string> { "Foo", "Bar" }; var called = false; target.Template = GetTemplate(); target.Items = items; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Remove; items.Remove("Bar"); Assert.True(called); } [Fact] public void LogicalChildren_Should_Not_Change_Instance_When_Template_Changed() { var target = new ItemsControl() { Template = GetTemplate(), }; var before = ((ILogical)target).LogicalChildren; target.Template = null; target.Template = GetTemplate(); var after = ((ILogical)target).LogicalChildren; Assert.NotNull(before); Assert.NotNull(after); Assert.Same(before, after); } [Fact] public void Empty_Class_Should_Initially_Be_Applied() { var target = new ItemsControl() { Template = GetTemplate(), }; Assert.True(target.Classes.Contains(":empty")); } [Fact] public void Empty_Class_Should_Be_Cleared_When_Items_Added() { var target = new ItemsControl() { Template = GetTemplate(), Items = new[] { 1, 2, 3 }, }; Assert.False(target.Classes.Contains(":empty")); } [Fact] public void Empty_Class_Should_Be_Set_When_Empty_Collection_Set() { var target = new ItemsControl() { Template = GetTemplate(), Items = new[] { 1, 2, 3 }, }; target.Items = new int[0]; Assert.True(target.Classes.Contains(":empty")); } [Fact] public void Setting_Presenter_Explicitly_Should_Set_Item_Parent() { var target = new TestItemsControl(); var child = new Control(); var presenter = new ItemsPresenter { TemplatedParent = target, [~ItemsPresenter.ItemsProperty] = target[~ItemsControl.ItemsProperty], }; presenter.ApplyTemplate(); target.Presenter = presenter; target.Items = new[] { child }; target.ApplyTemplate(); Assert.Equal(target, child.Parent); Assert.Equal(target, ((ILogical)child).LogicalParent); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Item("Bar"), new TextBlock { Text = "Baz" }, new ListBoxItem { Content = "Qux" }, }; var target = new ItemsControl { Template = GetTemplate(), DataContext = "Base", DataTemplates = new DataTemplates { new FuncDataTemplate<Item>(x => new Button { Content = x }) }, Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var dataContexts = target.Presenter.Panel.Children .Do(x => (x as ContentPresenter)?.UpdateChild()) .Cast<Control>() .Select(x => x.DataContext) .ToList(); Assert.Equal( new object[] { items[0], items[1], "Base", "Base" }, dataContexts); } [Fact] public void MemberSelector_Should_Select_Member() { var target = new ItemsControl { Template = GetTemplate(), Items = new[] { new Item("Foo"), new Item("Bar") }, MemberSelector = new FuncMemberSelector<Item, string>(x => x.Value), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var text = target.Presenter.Panel.Children .Cast<ContentPresenter>() .Select(x => x.Content) .ToList(); Assert.Equal(new[] { "Foo", "Bar" }, text); } [Fact] public void Control_Item_Should_Not_Be_NameScope() { var items = new object[] { new TextBlock(), }; var target = new ItemsControl { Template = GetTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.Null(NameScope.GetNameScope((TextBlock)item)); } [Fact] public void DataTemplate_Created_Content_Should_Be_NameScope() { var items = new object[] { "foo", }; var target = new ItemsControl { Template = GetTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.LogicalChildren[0]; container.UpdateChild(); Assert.NotNull(NameScope.GetNameScope((TextBlock)container.Child)); } private class Item { public Item(string value) { Value = value; } public string Value { get; } } private FuncControlTemplate GetTemplate() { return new FuncControlTemplate<ItemsControl>(parent => { return new Border { Background = new Media.SolidColorBrush(0xffffffff), Child = new ItemsPresenter { Name = "PART_ItemsPresenter", MemberSelector = parent.MemberSelector, [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], } }; }); } private class TestItemsControl : ItemsControl { public new IItemsPresenter Presenter { get { return base.Presenter; } set { base.Presenter = 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; using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); Assert.Equal(default(AsyncValueTaskMethodBuilder<int>), b); // implementation detail being verified } [Fact] public void SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.True(vt.IsCompletedSuccessfully); Assert.False(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); ValueTask<int> vt = b.Task; b.SetResult(42); Assert.True(vt.IsCompletedSuccessfully); Assert.True(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new OperationCanceledException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AwaitOnCompleted_InvokesStateMachineMethods(bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var ignored = b.Task; var callbackCompleted = new TaskCompletionSource<bool>(); IAsyncStateMachine foundSm = null; var dsm = new DelegateStateMachine { MoveNextDelegate = () => callbackCompleted.SetResult(true), SetStateMachineDelegate = sm => foundSm = sm }; TaskAwaiter t = Task.CompletedTask.GetAwaiter(); if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } await callbackCompleted.Task; Assert.Equal(dsm, foundSm); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); Assert.True(WrapsTask(b.Task)); Assert.Equal(42, b.Task.Result); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22506", TargetFrameworkMonikers.UapAot)] public void SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); b.SetStateMachine(new DelegateStateMachine()); } [Fact] public void Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); ValueTask<int> vt = b.Task; Assert.False(WrapsTask(vt)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42, await ValueTaskReturningAsyncMethod(42)); ValueTask<int> vt = ValueTaskReturningAsyncMethod(84); Assert.Equal(yields > 0, WrapsTask(vt)); Assert.Equal(84, await vt); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) await Task.Yield(); return result; } } /// <summary>Gets whether the ValueTask has a non-null Task.</summary> private static bool WrapsTask<T>(ValueTask<T> vt) => ReferenceEquals(vt.AsTask(), vt.AsTask()); private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); internal Action<IAsyncStateMachine> SetStateMachineDelegate; public void SetStateMachine(IAsyncStateMachine stateMachine) => SetStateMachineDelegate?.Invoke(stateMachine); } } }
/* ----------------------------------------------------------------------------- * Displayer.cs * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Sat Dec 18 07:35:23 GMT 2021 * * ----------------------------------------------------------------------------- */ using System; using System.Collections.Generic; using Nethereum.Siwe.Core; internal class MessageExtractor:Visitor { public SiweMessage SiweMessage { get; private set; } public MessageExtractor() { SiweMessage = new SiweMessage(); SiweMessage.Resources = new List<string>(); } public Object Visit(Rule_sign_in_with_ethereum rule) { return VisitRules(rule.rules); } public Object Visit(Rule_domain rule) { SiweMessage.Domain = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_address rule) { SiweMessage.Address = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_statement rule) { SiweMessage.Statement = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_version rule) { SiweMessage.Version = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_nonce rule) { SiweMessage.Nonce = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_issued_at rule) { SiweMessage.IssuedAt = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_expiration_time rule) { SiweMessage.ExpirationTime = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_not_before rule) { SiweMessage.NotBefore = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_request_id rule) { SiweMessage.RequestId = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_chain_id rule) { SiweMessage.ChainId = rule.spelling; return VisitRules(rule.rules); } public Object Visit(Rule_resources rule) { return VisitRules(rule.rules); } public Object Visit(Rule_resource rule) { //skip "- " SiweMessage.Resources.Add(rule.spelling.Substring(2)); return VisitRules(rule.rules); } private int _uriCount = 0; public Object Visit(Rule_URI rule) { //first uri found not to be confused with resources if (_uriCount == 0) { SiweMessage.Uri = rule.spelling; _uriCount = 1; } return VisitRules(rule.rules); } public Object Visit(Rule_hier_part rule) { return VisitRules(rule.rules); } public Object Visit(Rule_scheme rule) { return VisitRules(rule.rules); } public Object Visit(Rule_authority rule) { return VisitRules(rule.rules); } public Object Visit(Rule_userinfo rule) { return VisitRules(rule.rules); } public Object Visit(Rule_host rule) { return VisitRules(rule.rules); } public Object Visit(Rule_port rule) { return VisitRules(rule.rules); } public Object Visit(Rule_IP_literal rule) { return VisitRules(rule.rules); } public Object Visit(Rule_IPvFuture rule) { return VisitRules(rule.rules); } public Object Visit(Rule_IPv6address rule) { return VisitRules(rule.rules); } public Object Visit(Rule_h16 rule) { return VisitRules(rule.rules); } public Object Visit(Rule_ls32 rule) { return VisitRules(rule.rules); } public Object Visit(Rule_IPv4address rule) { return VisitRules(rule.rules); } public Object Visit(Rule_dec_octet rule) { return VisitRules(rule.rules); } public Object Visit(Rule_reg_name rule) { return VisitRules(rule.rules); } public Object Visit(Rule_path_abempty rule) { return VisitRules(rule.rules); } public Object Visit(Rule_path_absolute rule) { return VisitRules(rule.rules); } public Object Visit(Rule_path_rootless rule) { return VisitRules(rule.rules); } public Object Visit(Rule_path_empty rule) { return VisitRules(rule.rules); } public Object Visit(Rule_segment rule) { return VisitRules(rule.rules); } public Object Visit(Rule_segment_nz rule) { return VisitRules(rule.rules); } public Object Visit(Rule_pchar rule) { return VisitRules(rule.rules); } public Object Visit(Rule_query rule) { return VisitRules(rule.rules); } public Object Visit(Rule_fragment rule) { return VisitRules(rule.rules); } public Object Visit(Rule_pct_encoded rule) { return VisitRules(rule.rules); } public Object Visit(Rule_unreserved rule) { return VisitRules(rule.rules); } public Object Visit(Rule_reserved rule) { return VisitRules(rule.rules); } public Object Visit(Rule_gen_delims rule) { return VisitRules(rule.rules); } public Object Visit(Rule_sub_delims rule) { return VisitRules(rule.rules); } public Object Visit(Rule_date_fullyear rule) { return VisitRules(rule.rules); } public Object Visit(Rule_date_month rule) { return VisitRules(rule.rules); } public Object Visit(Rule_date_mday rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_hour rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_minute rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_second rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_secfrac rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_numoffset rule) { return VisitRules(rule.rules); } public Object Visit(Rule_time_offset rule) { return VisitRules(rule.rules); } public Object Visit(Rule_partial_time rule) { return VisitRules(rule.rules); } public Object Visit(Rule_full_date rule) { return VisitRules(rule.rules); } public Object Visit(Rule_full_time rule) { return VisitRules(rule.rules); } public Object Visit(Rule_date_time rule) { return VisitRules(rule.rules); } public Object Visit(Rule_ALPHA rule) { return VisitRules(rule.rules); } public Object Visit(Rule_LF rule) { return VisitRules(rule.rules); } public Object Visit(Rule_DIGIT rule) { return VisitRules(rule.rules); } public Object Visit(Rule_HEXDIG rule) { return VisitRules(rule.rules); } public Object Visit(Terminal_StringValue value) { //Console.Write(value.spelling); return null; } public Object Visit(Terminal_StringExactValue value) { //Console.Write(value.spelling); return null; } public Object Visit(Terminal_NumericValue value) { //Console.Write(value.spelling); return null; } private Object VisitRules(List<Rule> rules) { foreach (Rule rule in rules) rule.Accept(this); return null; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
// // 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.LayoutRenderers { using System; using System.ComponentModel; using System.IO; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// The call site (class name, method name and source information). /// </summary> [LayoutRenderer("callsite")] [ThreadAgnostic] [ThreadSafe] public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace { /// <summary> /// Initializes a new instance of the <see cref="CallSiteLayoutRenderer" /> class. /// </summary> public CallSiteLayoutRenderer() { ClassName = true; MethodName = true; CleanNamesOfAnonymousDelegates = false; IncludeNamespace = true; #if !SILVERLIGHT FileName = false; IncludeSourcePath = true; #endif } /// <summary> /// Gets or sets a value indicating whether to render the class name. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(true)] public bool ClassName { get; set; } /// <summary> /// Gets or sets a value indicating whether to render the include the namespace with <see cref="ClassName"/>. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(true)] public bool IncludeNamespace { get; set; } /// <summary> /// Gets or sets a value indicating whether to render the method name. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(true)] public bool MethodName { get; set; } /// <summary> /// Gets or sets a value indicating whether the method name will be cleaned up if it is detected as an anonymous delegate. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(false)] public bool CleanNamesOfAnonymousDelegates { get; set; } /// <summary> /// Gets or sets a value indicating whether the method and class names will be cleaned up if it is detected as an async continuation /// (everything after an await-statement inside of an async method). /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(false)] public bool CleanNamesOfAsyncContinuations { get; set; } /// <summary> /// Gets or sets the number of frames to skip. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(0)] public int SkipFrames { get; set; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to render the source file name and line number. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(false)] public bool FileName { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source file path. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(true)] public bool IncludeSourcePath { get; set; } #endif /// <summary> /// Logger should capture StackTrace, if it was not provided manually /// </summary> [DefaultValue(true)] public bool CaptureStackTrace { get; set; } = true; /// <summary> /// Gets the level of stack trace information required by the implementing class. /// </summary> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (!CaptureStackTrace) { return StackTraceUsage.None; } #if !SILVERLIGHT if (FileName) { return StackTraceUsage.Max; } #endif return StackTraceUsage.WithoutSource; } } /// <summary> /// Renders the call site and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (logEvent.CallSiteInformation != null) { if (ClassName || MethodName) { var method = logEvent.CallSiteInformation.GetCallerStackFrameMethod(SkipFrames); if (ClassName) { string className = logEvent.CallSiteInformation.GetCallerClassName(method, IncludeNamespace, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); if (string.IsNullOrEmpty(className)) className = "<no type>"; builder.Append(className); } if (MethodName) { string methodName = logEvent.CallSiteInformation.GetCallerMemberName(method, false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); if (string.IsNullOrEmpty(methodName)) methodName = "<no method>"; if (ClassName) { builder.Append("."); } builder.Append(methodName); } } #if !SILVERLIGHT if (FileName) { string fileName = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames); if (!string.IsNullOrEmpty(fileName)) { int lineNumber = logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames); AppendFileName(builder, fileName, lineNumber); } } #endif } } #if !SILVERLIGHT private void AppendFileName(StringBuilder builder, string fileName, int lineNumber) { builder.Append("("); if (IncludeSourcePath) { builder.Append(fileName); } else { builder.Append(Path.GetFileName(fileName)); } builder.Append(":"); builder.AppendInvariant(lineNumber); builder.Append(")"); } #endif } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; namespace FileHelpers.Options { using System.Collections.Generic; /// <summary> /// This class allows you to set some options of the records at runtime. /// With these options the library is now more flexible than ever. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public abstract class RecordOptions { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal IRecordInfo mRecordInfo; /// <summary> /// This class allows you to set some options of the records at runtime. /// With these options the library is now more flexible than ever. /// </summary> /// <param name="info">Record information</param> internal RecordOptions(IRecordInfo info) { mRecordInfo = info; mRecordConditionInfo = new RecordConditionInfo(info); mIgnoreCommentInfo = new IgnoreCommentInfo(info); } /// <summary> /// Copies the fields in the current recordinfo. /// </summary> [Pure] public FieldBaseCollection Fields { get { return new FieldBaseCollection(mRecordInfo.Fields); } } /// <summary> /// Removes the filed from the underlying <seealso cref="IRecordInfo"/>. /// </summary> public void RemoveField(string fieldname) { mRecordInfo.RemoveField(fieldname); } /// <summary> /// The number of fields of the record type. /// </summary> public int FieldCount { get { return mRecordInfo.FieldCount; } } // <summary>The number of fields of the record type.</summary> //[System.Runtime.CompilerServices.IndexerName("FieldNames")] //public string this[int index] //{ // get // { // return mRecordInfo.mFields[index].mFieldInfo.Name; // } //} [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string[] mFieldNames; /// <summary> /// Returns an string array with the fields names. /// Note : Do NOT change the values of the array, clone it first if needed /// </summary> /// <returns>An string array with the fields names.</returns> public string[] FieldsNames { get { if (mFieldNames == null) { mFieldNames = new string[mRecordInfo.FieldCount]; for (int i = 0; i < mFieldNames.Length; i++) mFieldNames[i] = mRecordInfo.Fields[i].FieldFriendlyName; } return mFieldNames; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Type[] mFieldTypes; /// <summary> /// Returns a Type[] array with the fields types. /// Note : Do NOT change the values of the array, clone it first if /// needed /// </summary> /// <returns>An Type[] array with the fields types.</returns> public Type[] FieldsTypes { get { if (mFieldTypes == null) { mFieldTypes = new Type[mRecordInfo.FieldCount]; for (int i = 0; i < mFieldTypes.Length; i++) mFieldTypes[i] = mRecordInfo.Fields[i].FieldInfo.FieldType; } return mFieldTypes; } } /// <summary> /// Indicates the number of first lines to be discarded. /// </summary> public int IgnoreFirstLines { get { return mRecordInfo.IgnoreFirst; } set { PositiveValue(value); mRecordInfo.IgnoreFirst = value; } } /// <summary> /// Indicates the number of lines at the end of file to be discarded. /// </summary> public int IgnoreLastLines { get { return mRecordInfo.IgnoreLast; } set { PositiveValue(value); mRecordInfo.IgnoreLast = value; } } /// <summary> /// Indicates that the engine must ignore the empty lines while /// reading. /// </summary> public bool IgnoreEmptyLines { get { return mRecordInfo.IgnoreEmptyLines; } set { mRecordInfo.IgnoreEmptyLines = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly RecordConditionInfo mRecordConditionInfo; /// <summary> /// Used to tell the engine which records must be included or excluded /// while reading. /// </summary> public RecordConditionInfo RecordCondition { get { return mRecordConditionInfo; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IgnoreCommentInfo mIgnoreCommentInfo; /// <summary> /// Indicates that the engine must ignore the lines with this comment /// marker. /// </summary> public IgnoreCommentInfo IgnoreCommentedLines { get { return mIgnoreCommentInfo; } } /// <summary> /// Used to tell the engine which records must be included or excluded /// while reading. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class RecordConditionInfo { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IRecordInfo mRecordInfo; /// <summary> /// Used to tell the engine which records must be included or /// excluded while reading. /// </summary> /// <param name="ri">Record information</param> internal RecordConditionInfo(IRecordInfo ri) { mRecordInfo = ri; } /// <summary> /// The condition used to include or exclude records. /// </summary> public RecordCondition Condition { get { return mRecordInfo.RecordCondition; } set { mRecordInfo.RecordCondition = value; } } /// <summary> /// The selector used by the <see cref="RecordCondition"/>. /// </summary> public string Selector { get { return mRecordInfo.RecordConditionSelector; } set { mRecordInfo.RecordConditionSelector = value; } } } /// <summary> /// Indicates that the engine must ignore the lines with this comment /// marker. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class IgnoreCommentInfo { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IRecordInfo mRecordInfo; /// <summary> /// Indicates that the engine must ignore the lines with this /// comment marker. /// </summary> /// <param name="ri">Record information</param> internal IgnoreCommentInfo(IRecordInfo ri) { mRecordInfo = ri; } /// <summary> /// <para>Indicates that the engine must ignore the lines with this /// comment marker.</para> /// <para>An empty string or null indicates that the engine doesn't /// look for comments</para> /// </summary> public string CommentMarker { get { return mRecordInfo.CommentMarker; } set { if (value != null) value = value.Trim(); mRecordInfo.CommentMarker = value; } } /// <summary> /// Indicates if the comment can have spaces or tabs at left (true /// by default) /// </summary> public bool InAnyPlace { get { return mRecordInfo.CommentAnyPlace; } set { mRecordInfo.CommentAnyPlace = value; } } } /// <summary> /// Allows the creating of a record string of the given record. Is /// useful when your want to log errors to a plan text file or database /// </summary> /// <param name="record"> /// The record that will be transformed to string /// </param> /// <returns>The string representation of the current record</returns> public string RecordToString(object record) { return mRecordInfo.Operations.RecordToString(record); } /// <summary> /// Allows to get an object[] with the values of the fields in the <paramref name="record"/> /// </summary> /// <param name="record">The record that will be transformed to object[]</param> /// <returns>The object[] with the values of the fields in the current record</returns> public object[] RecordToValues(object record) { return mRecordInfo.Operations.RecordToValues(record); } /// <summary> /// Check an integer value is positive (0 or greater) /// </summary> /// <param name="val">Integer to test</param> private static void PositiveValue(int val) { if (val < 0) throw new ArgumentException("The value must be greater than or equal to 0."); } } /// <summary>An amount of <seealso cref="FieldBase"/>.</summary> public sealed class FieldBaseCollection : List<FieldBase> { internal FieldBaseCollection(FieldBase[] fields) : base(fields) {} } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using System.Collections.Generic; using BEPUphysics.CollisionShapes; using BEPUutilities; using BEPUphysics.BroadPhaseEntries; using BEPUphysics.CollisionShapes.ConvexShapes; using BEPUphysics.BroadPhaseEntries.MobileCollidables; using BEPUutilities.DataStructures; namespace Voxalia.Shared.Collision { public class FullChunkShape : CollisionShape { public const int CHUNK_SIZE = 30; public FullChunkShape(BlockInternal[] blocks) { Blocks = blocks; } public BlockInternal[] Blocks = null; public int BlockIndex(int x, int y, int z) { return z * CHUNK_SIZE * CHUNK_SIZE + y * CHUNK_SIZE + x; } public static Vector3i[] ReachStarts = new Vector3i[] { new Vector3i(0, 0, 1),//ZP_ZM = 0, new Vector3i(0, 0, 1),//ZP_XP = 1, new Vector3i(0, 0, 1),//ZP_YP = 2, new Vector3i(0, 0, 1),//ZP_XM = 3, new Vector3i(0, 0, 1),//ZP_YM = 4, new Vector3i(0, 0, 1),//ZM_XP = 5, new Vector3i(0, 0, -1),//ZM_YP = 6, new Vector3i(0, 0, -1),//ZM_XM = 7, new Vector3i(0, 0, -1),//ZM_YM = 8, new Vector3i(1, 0, 0),//XP_YP = 9, new Vector3i(1, 0, 0),//XP_YM = 10, new Vector3i(1, 0, 0),//XP_XM = 11, new Vector3i(-1, 0, 0),//XM_YP = 12, new Vector3i(-1, 0, 0),//XM_YM = 13, new Vector3i(0, 1, 0)//YP_YM = 14 }; public static Vector3i[] ReachEnds = new Vector3i[] { new Vector3i(0, 0, -1),//ZP_ZM = 0, new Vector3i(1, 0, 0),//ZP_XP = 1, new Vector3i(0, 1, 0),//ZP_YP = 2, new Vector3i(-1, 0, 0),//ZP_XM = 3, new Vector3i(0, -1, 0),//ZP_YM = 4, new Vector3i(1, 0, 0),//ZM_XP = 5, new Vector3i(0, 1, 0),//ZM_YP = 6, new Vector3i(-1, 0, 0),//ZM_XM = 7, new Vector3i(0, -1, 0),//ZM_YM = 8, new Vector3i(0, 1, 0),//XP_YP = 9, new Vector3i(0, -1, 0),//XP_YM = 10, new Vector3i(-1, 0, 0),//XP_XM = 11, new Vector3i(0, 1, 0),//XM_YP = 12, new Vector3i(0, -1, 0),//XM_YM = 13, new Vector3i(0, -1, 0)//YP_YM = 14 }; static Vector3i[] MoveDirs = new Vector3i[] { new Vector3i(-1, 0, 0), new Vector3i(1, 0, 0), new Vector3i(0, -1, 0), new Vector3i(0, 1, 0), new Vector3i(0, 0, -1), new Vector3i(0, 0, 1) }; public bool CanReach(Vector3i snorm, Vector3i enorm) { // Probably a better way to do this Vector3i low; Vector3i high; if (snorm.X == -1) { low = new Vector3i(0, 0, 0); high = new Vector3i(0, CHUNK_SIZE, CHUNK_SIZE); } else if (snorm.X == 1) { low = new Vector3i(CHUNK_SIZE, 0, 0); high = new Vector3i(CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE); } else if (snorm.Y == -1) { low = new Vector3i(0, 0, 0); high = new Vector3i(CHUNK_SIZE, 0, CHUNK_SIZE); } else if (snorm.Y == 1) { low = new Vector3i(0, CHUNK_SIZE, 0); high = new Vector3i(CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE); } else if (snorm.Z == -1) { low = new Vector3i(0, 0, 0); high = new Vector3i(CHUNK_SIZE, CHUNK_SIZE, 0); } else { low = new Vector3i(0, 0, CHUNK_SIZE); high = new Vector3i(CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE); } bool[] traced = new bool[CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE]; for (int x = low.X; x < high.X; x++) { for (int y = low.Y; y < high.Y; y++) { for (int z = low.Z; z < high.Z; z++) { if (PointCanReach(new Vector3i(x, y, z), enorm, traced)) { return true; } } } } return false; } public bool PointCanReach(Vector3i p, Vector3i enorm, bool[] traced) { Queue<Vector3i> toTrace = new Queue<Vector3i>(); toTrace.Enqueue(p); while (toTrace.Count > 0) { Vector3i tp = toTrace.Dequeue(); for (int i = 0; i < MoveDirs.Length; i++) { Vector3i np = tp + MoveDirs[i]; if (np.X < 0 || np.Y < 0 || np.Z < 0 || np.X >= CHUNK_SIZE || np.Y >= CHUNK_SIZE || np.Z >= CHUNK_SIZE) { if ((np.X < 0 && enorm.X == -1) || (np.X >= CHUNK_SIZE && enorm.X == 1) || (np.Y < 0 && enorm.Y == -1) || (np.Y >= CHUNK_SIZE && enorm.Y == 1) || (np.Y < 0 && enorm.Y == -1) || (np.Y >= CHUNK_SIZE && enorm.Y == 1)) { return true; } continue; } int id = BlockIndex(np.X, np.Y, np.Z); int id2 = BlockIndex(tp.X, tp.Y, tp.Z); if (!traced[BlockIndex(tp.X, tp.Y, tp.Z)] && !Blocks[id].IsOpaque()) { toTrace.Enqueue(np); traced[id] = true; } } } return false; } public ConvexShape ShapeAt(int x, int y, int z, out Vector3 offs) { if (x < 0 || y < 0 || z < 0 || x >= CHUNK_SIZE || y >= CHUNK_SIZE || z >= CHUNK_SIZE) { offs = new Vector3(double.NaN, double.NaN, double.NaN); return null; } Location loffs; BlockInternal bi = Blocks[BlockIndex(x, y, z)]; ConvexShape shape = (ConvexShape)BlockShapeRegistry.BSD[bi.BlockData].GetShape(bi.Damage, out loffs, false); offs = loffs.ToBVector(); return shape; } public bool ConvexCast(ConvexShape castShape, ref RigidTransform startingTransform, ref Vector3 sweepnorm, double slen, MaterialSolidity solidness, out RayHit hit) { BoundingBox bb; RigidTransform rot = new RigidTransform(Vector3.Zero, startingTransform.Orientation); castShape.GetBoundingBox(ref rot, out bb); double adv = 0.1f; double max = slen + adv; bool gotOne = false; RayHit BestRH = default(RayHit); Vector3 sweep = sweepnorm * slen; for (double f = 0; f < max; f += adv) { Vector3 c = startingTransform.Position + sweepnorm * f; int mx = (int)Math.Ceiling(c.X + bb.Max.X); for (int x = (int)Math.Floor(c.X + bb.Min.X); x <= mx; x++) { if (x < 0 || x >= CHUNK_SIZE) { continue; } int my = (int)Math.Ceiling(c.Y + bb.Max.Y); for (int y = (int)Math.Floor(c.Y + bb.Min.Y); y <= my; y++) { if (y < 0 || y >= CHUNK_SIZE) { continue; } int mz = (int)Math.Ceiling(c.Z + bb.Max.Z); for (int z = (int)Math.Floor(c.Z + bb.Min.Z); z <= mz; z++) { if (z < 0 || z >= CHUNK_SIZE) { continue; } BlockInternal bi = Blocks[BlockIndex(x, y, z)]; if (solidness.HasFlag(((Material)bi.BlockMaterial).GetSolidity())) { Location offs; EntityShape es = BlockShapeRegistry.BSD[bi.BlockData].GetShape(bi.Damage, out offs, false); if (es == null) { continue; } Vector3 adj = new Vector3(x + (double)offs.X, y + (double)offs.Y, z + (double)offs.Z); EntityCollidable coll = es.GetCollidableInstance(); //coll.LocalPosition = adj; RigidTransform rt = new RigidTransform(Vector3.Zero, Quaternion.Identity); coll.LocalPosition = Vector3.Zero; coll.WorldTransform = rt; coll.UpdateBoundingBoxForTransform(ref rt); RayHit rhit; RigidTransform adjusted = new RigidTransform(startingTransform.Position - adj, startingTransform.Orientation); bool b = coll.ConvexCast(castShape, ref adjusted, ref sweep, out rhit); if (b && (!gotOne || rhit.T * slen < BestRH.T) && rhit.T >= 0) { gotOne = true; BestRH = rhit; BestRH.Location += adj; BestRH.T *= slen; // TODO: ??? BestRH.Normal = -BestRH.Normal; // TODO: WHY?! } } } } } if (gotOne) { hit = BestRH; return true; } } hit = new RayHit() { Location = startingTransform.Position + sweep, Normal = new Vector3(0, 0, 0), T = slen }; return false; } BoxShape RayCastShape = new BoxShape(0.1f, 0.1f, 0.1f); public bool RayCast(ref Ray ray, double maximumLength, MaterialSolidity solidness, out RayHit hit) { // TODO: Original special ray code! RigidTransform rt = new RigidTransform(ray.Position, Quaternion.Identity); Vector3 sweep = ray.Direction; return ConvexCast(RayCastShape, ref rt, ref sweep, maximumLength, solidness, out hit); } // TODO: Optimize me! public void GetOverlaps(Vector3 gridPosition, BoundingBox boundingBox, ref QuickList<Vector3i> overlaps) { BoundingBox b2 = new BoundingBox(); Vector3.Subtract(ref boundingBox.Min, ref gridPosition, out b2.Min); Vector3.Subtract(ref boundingBox.Max, ref gridPosition, out b2.Max); var min = new Vector3i { X = Math.Max(0, (int)b2.Min.X), Y = Math.Max(0, (int)b2.Min.Y), Z = Math.Max(0, (int)b2.Min.Z) }; var max = new Vector3i { X = Math.Min(CHUNK_SIZE - 1, (int)b2.Max.X), Y = Math.Min(CHUNK_SIZE - 1, (int)b2.Max.Y), Z = Math.Min(CHUNK_SIZE - 1, (int)b2.Max.Z) }; for (int x = min.X; x <= max.X; x++) { for (int y = min.Y; y <= max.Y; y++) { for (int z = min.Z; z <= max.Z; z++) { if (Blocks[BlockIndex(x, y, z)].Material.GetSolidity() == MaterialSolidity.FULLSOLID) { overlaps.Add(new Vector3i { X = x, Y = y, Z = z }); } } } } } } }
namespace groupmanager { partial class frmGroupInfo { /// <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.tabs = new System.Windows.Forms.TabControl(); this.tabGeneral = new System.Windows.Forms.TabPage(); this.grpPreferences = new System.Windows.Forms.GroupBox(); this.chkMature = new System.Windows.Forms.CheckBox(); this.numFee = new System.Windows.Forms.NumericUpDown(); this.chkGroupNotices = new System.Windows.Forms.CheckBox(); this.chkFee = new System.Windows.Forms.CheckBox(); this.chkOpenEnrollment = new System.Windows.Forms.CheckBox(); this.chkPublish = new System.Windows.Forms.CheckBox(); this.chkShow = new System.Windows.Forms.CheckBox(); this.lstMembers = new System.Windows.Forms.ListView(); this.colName = new System.Windows.Forms.ColumnHeader(); this.colTitle = new System.Windows.Forms.ColumnHeader(); this.colLasLogin = new System.Windows.Forms.ColumnHeader(); this.txtCharter = new System.Windows.Forms.TextBox(); this.lblFoundedBy = new System.Windows.Forms.Label(); this.lblGroupName = new System.Windows.Forms.Label(); this.picInsignia = new System.Windows.Forms.PictureBox(); this.tabMembersRoles = new System.Windows.Forms.TabPage(); this.tabsMRA = new System.Windows.Forms.TabControl(); this.tabMembers = new System.Windows.Forms.TabPage(); this.cmdEject = new System.Windows.Forms.Button(); this.lstMembers2 = 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.chkListRoles = new System.Windows.Forms.CheckedListBox(); this.treeAbilities = new System.Windows.Forms.TreeView(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.tabRoles = new System.Windows.Forms.TabPage(); this.tabAbilities = new System.Windows.Forms.TabPage(); this.tabNotices = new System.Windows.Forms.TabPage(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.cmdRefreshNotices = new System.Windows.Forms.Button(); this.lstNotices = new System.Windows.Forms.ListView(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.columnHeader5 = new System.Windows.Forms.ColumnHeader(); this.columnHeader6 = new System.Windows.Forms.ColumnHeader(); this.tabProposals = new System.Windows.Forms.TabPage(); this.tabLand = new System.Windows.Forms.TabPage(); this.tabsMoney = new System.Windows.Forms.TabControl(); this.tabPlanning = new System.Windows.Forms.TabPage(); this.txtPlanning = new System.Windows.Forms.TextBox(); this.tabDetails = new System.Windows.Forms.TabPage(); this.txtDetails = new System.Windows.Forms.TextBox(); this.tabSales = new System.Windows.Forms.TabPage(); this.txtSales = new System.Windows.Forms.TextBox(); this.txtContribution = new System.Windows.Forms.TextBox(); this.lblLandAvailable = new System.Windows.Forms.Label(); this.lblLandInUse = new System.Windows.Forms.Label(); this.lblTotalContribution = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.lstLand = new System.Windows.Forms.ListView(); this.columnHeader7 = new System.Windows.Forms.ColumnHeader(); this.columnHeader8 = new System.Windows.Forms.ColumnHeader(); this.columnHeader9 = new System.Windows.Forms.ColumnHeader(); this.cmdApply = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdOK = new System.Windows.Forms.Button(); this.cmdRefresh = new System.Windows.Forms.Button(); this.tabs.SuspendLayout(); this.tabGeneral.SuspendLayout(); this.grpPreferences.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numFee)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picInsignia)).BeginInit(); this.tabMembersRoles.SuspendLayout(); this.tabsMRA.SuspendLayout(); this.tabMembers.SuspendLayout(); this.tabNotices.SuspendLayout(); this.tabLand.SuspendLayout(); this.tabsMoney.SuspendLayout(); this.tabPlanning.SuspendLayout(); this.tabDetails.SuspendLayout(); this.tabSales.SuspendLayout(); this.SuspendLayout(); // // tabs // this.tabs.Controls.Add(this.tabGeneral); this.tabs.Controls.Add(this.tabMembersRoles); this.tabs.Controls.Add(this.tabNotices); this.tabs.Controls.Add(this.tabProposals); this.tabs.Controls.Add(this.tabLand); this.tabs.Location = new System.Drawing.Point(6, 7); this.tabs.Name = "tabs"; this.tabs.SelectedIndex = 0; this.tabs.Size = new System.Drawing.Size(417, 507); this.tabs.TabIndex = 9; // // tabGeneral // this.tabGeneral.Controls.Add(this.grpPreferences); this.tabGeneral.Controls.Add(this.lstMembers); this.tabGeneral.Controls.Add(this.txtCharter); this.tabGeneral.Controls.Add(this.lblFoundedBy); this.tabGeneral.Controls.Add(this.lblGroupName); this.tabGeneral.Controls.Add(this.picInsignia); this.tabGeneral.Location = new System.Drawing.Point(4, 22); this.tabGeneral.Name = "tabGeneral"; this.tabGeneral.Padding = new System.Windows.Forms.Padding(3); this.tabGeneral.Size = new System.Drawing.Size(409, 481); this.tabGeneral.TabIndex = 0; this.tabGeneral.Text = "General"; this.tabGeneral.UseVisualStyleBackColor = true; // // grpPreferences // this.grpPreferences.Controls.Add(this.chkMature); this.grpPreferences.Controls.Add(this.numFee); this.grpPreferences.Controls.Add(this.chkGroupNotices); this.grpPreferences.Controls.Add(this.chkFee); this.grpPreferences.Controls.Add(this.chkOpenEnrollment); this.grpPreferences.Controls.Add(this.chkPublish); this.grpPreferences.Controls.Add(this.chkShow); this.grpPreferences.Location = new System.Drawing.Point(10, 353); this.grpPreferences.Name = "grpPreferences"; this.grpPreferences.Size = new System.Drawing.Size(393, 122); this.grpPreferences.TabIndex = 14; this.grpPreferences.TabStop = false; this.grpPreferences.Text = "Group Preferences"; // // chkMature // this.chkMature.AutoSize = true; this.chkMature.Location = new System.Drawing.Point(162, 19); this.chkMature.Name = "chkMature"; this.chkMature.Size = new System.Drawing.Size(95, 17); this.chkMature.TabIndex = 6; this.chkMature.Text = "Mature publish"; this.chkMature.UseVisualStyleBackColor = true; // // numFee // this.numFee.Location = new System.Drawing.Point(162, 87); this.numFee.Name = "numFee"; this.numFee.Size = new System.Drawing.Size(82, 20); this.numFee.TabIndex = 5; // // chkGroupNotices // this.chkGroupNotices.AutoSize = true; this.chkGroupNotices.Location = new System.Drawing.Point(250, 87); this.chkGroupNotices.Name = "chkGroupNotices"; this.chkGroupNotices.Size = new System.Drawing.Size(137, 17); this.chkGroupNotices.TabIndex = 4; this.chkGroupNotices.Text = "Receive Group Notices"; this.chkGroupNotices.UseVisualStyleBackColor = true; // // chkFee // this.chkFee.AutoSize = true; this.chkFee.Location = new System.Drawing.Point(36, 88); this.chkFee.Name = "chkFee"; this.chkFee.Size = new System.Drawing.Size(114, 17); this.chkFee.TabIndex = 3; this.chkFee.Text = "Enrollment Fee: L$"; this.chkFee.UseVisualStyleBackColor = true; // // chkOpenEnrollment // this.chkOpenEnrollment.AutoSize = true; this.chkOpenEnrollment.Location = new System.Drawing.Point(16, 65); this.chkOpenEnrollment.Name = "chkOpenEnrollment"; this.chkOpenEnrollment.Size = new System.Drawing.Size(104, 17); this.chkOpenEnrollment.TabIndex = 2; this.chkOpenEnrollment.Text = "Open Enrollment"; this.chkOpenEnrollment.UseVisualStyleBackColor = true; // // chkPublish // this.chkPublish.AutoSize = true; this.chkPublish.Location = new System.Drawing.Point(16, 42); this.chkPublish.Name = "chkPublish"; this.chkPublish.Size = new System.Drawing.Size(116, 17); this.chkPublish.TabIndex = 1; this.chkPublish.Text = "Publish on the web"; this.chkPublish.UseVisualStyleBackColor = true; // // chkShow // this.chkShow.AutoSize = true; this.chkShow.Location = new System.Drawing.Point(16, 19); this.chkShow.Name = "chkShow"; this.chkShow.Size = new System.Drawing.Size(116, 17); this.chkShow.TabIndex = 0; this.chkShow.Text = "Show In Group List"; this.chkShow.UseVisualStyleBackColor = true; // // lstMembers // this.lstMembers.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colName, this.colTitle, this.colLasLogin}); this.lstMembers.Location = new System.Drawing.Point(7, 221); this.lstMembers.Name = "lstMembers"; this.lstMembers.Size = new System.Drawing.Size(396, 126); this.lstMembers.TabIndex = 13; this.lstMembers.UseCompatibleStateImageBehavior = false; this.lstMembers.View = System.Windows.Forms.View.Details; // // colName // this.colName.Text = "Member Name"; this.colName.Width = 166; // // colTitle // this.colTitle.Text = "Title"; this.colTitle.Width = 127; // // colLasLogin // this.colLasLogin.Text = "Last Login"; this.colLasLogin.Width = 95; // // txtCharter // this.txtCharter.Location = new System.Drawing.Point(146, 42); this.txtCharter.Multiline = true; this.txtCharter.Name = "txtCharter"; this.txtCharter.Size = new System.Drawing.Size(257, 173); this.txtCharter.TabIndex = 12; // // lblFoundedBy // this.lblFoundedBy.AutoSize = true; this.lblFoundedBy.Location = new System.Drawing.Point(7, 26); this.lblFoundedBy.Name = "lblFoundedBy"; this.lblFoundedBy.Size = new System.Drawing.Size(137, 13); this.lblFoundedBy.TabIndex = 11; this.lblFoundedBy.Text = "Founded by Group Founder"; // // lblGroupName // this.lblGroupName.AutoSize = true; this.lblGroupName.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblGroupName.Location = new System.Drawing.Point(7, 6); this.lblGroupName.Name = "lblGroupName"; this.lblGroupName.Size = new System.Drawing.Size(99, 17); this.lblGroupName.TabIndex = 10; this.lblGroupName.Text = "Group Name"; // // picInsignia // this.picInsignia.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picInsignia.Location = new System.Drawing.Point(10, 42); this.picInsignia.Name = "picInsignia"; this.picInsignia.Size = new System.Drawing.Size(130, 130); this.picInsignia.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picInsignia.TabIndex = 9; this.picInsignia.TabStop = false; // // tabMembersRoles // this.tabMembersRoles.Controls.Add(this.tabsMRA); this.tabMembersRoles.Location = new System.Drawing.Point(4, 22); this.tabMembersRoles.Name = "tabMembersRoles"; this.tabMembersRoles.Padding = new System.Windows.Forms.Padding(3); this.tabMembersRoles.Size = new System.Drawing.Size(409, 481); this.tabMembersRoles.TabIndex = 1; this.tabMembersRoles.Text = "Members & Roles"; this.tabMembersRoles.UseVisualStyleBackColor = true; // // tabsMRA // this.tabsMRA.Controls.Add(this.tabMembers); this.tabsMRA.Controls.Add(this.tabRoles); this.tabsMRA.Controls.Add(this.tabAbilities); this.tabsMRA.Location = new System.Drawing.Point(6, 6); this.tabsMRA.Name = "tabsMRA"; this.tabsMRA.SelectedIndex = 0; this.tabsMRA.Size = new System.Drawing.Size(400, 469); this.tabsMRA.TabIndex = 0; // // tabMembers // this.tabMembers.Controls.Add(this.cmdEject); this.tabMembers.Controls.Add(this.lstMembers2); this.tabMembers.Controls.Add(this.chkListRoles); this.tabMembers.Controls.Add(this.treeAbilities); this.tabMembers.Controls.Add(this.label2); this.tabMembers.Controls.Add(this.label1); this.tabMembers.Location = new System.Drawing.Point(4, 22); this.tabMembers.Name = "tabMembers"; this.tabMembers.Padding = new System.Windows.Forms.Padding(3); this.tabMembers.Size = new System.Drawing.Size(392, 443); this.tabMembers.TabIndex = 0; this.tabMembers.Text = "Members"; this.tabMembers.UseVisualStyleBackColor = true; // // cmdEject // this.cmdEject.Location = new System.Drawing.Point(258, 152); this.cmdEject.Name = "cmdEject"; this.cmdEject.Size = new System.Drawing.Size(128, 23); this.cmdEject.TabIndex = 15; this.cmdEject.Text = "Eject From Group"; this.cmdEject.UseVisualStyleBackColor = true; // // lstMembers2 // this.lstMembers2.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3}); this.lstMembers2.Location = new System.Drawing.Point(6, 6); this.lstMembers2.Name = "lstMembers2"; this.lstMembers2.Size = new System.Drawing.Size(380, 140); this.lstMembers2.TabIndex = 14; this.lstMembers2.UseCompatibleStateImageBehavior = false; this.lstMembers2.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Member Name"; this.columnHeader1.Width = 152; // // columnHeader2 // this.columnHeader2.Text = "Donated Tier"; this.columnHeader2.Width = 119; // // columnHeader3 // this.columnHeader3.Text = "Last Login"; this.columnHeader3.Width = 96; // // chkListRoles // this.chkListRoles.FormattingEnabled = true; this.chkListRoles.Location = new System.Drawing.Point(6, 196); this.chkListRoles.Name = "chkListRoles"; this.chkListRoles.Size = new System.Drawing.Size(147, 244); this.chkListRoles.TabIndex = 8; // // treeAbilities // this.treeAbilities.Location = new System.Drawing.Point(159, 196); this.treeAbilities.Name = "treeAbilities"; this.treeAbilities.Size = new System.Drawing.Size(227, 244); this.treeAbilities.TabIndex = 7; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(156, 180); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(82, 13); this.label2.TabIndex = 6; this.label2.Text = "Allowed Abilities"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 180); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 13); this.label1.TabIndex = 5; this.label1.Text = "Assigned Roles"; // // tabRoles // this.tabRoles.Location = new System.Drawing.Point(4, 22); this.tabRoles.Name = "tabRoles"; this.tabRoles.Padding = new System.Windows.Forms.Padding(3); this.tabRoles.Size = new System.Drawing.Size(392, 443); this.tabRoles.TabIndex = 1; this.tabRoles.Text = "Roles"; this.tabRoles.UseVisualStyleBackColor = true; // // tabAbilities // this.tabAbilities.Location = new System.Drawing.Point(4, 22); this.tabAbilities.Name = "tabAbilities"; this.tabAbilities.Size = new System.Drawing.Size(392, 443); this.tabAbilities.TabIndex = 2; this.tabAbilities.Text = "Abilities"; this.tabAbilities.UseVisualStyleBackColor = true; // // tabNotices // this.tabNotices.Controls.Add(this.textBox1); this.tabNotices.Controls.Add(this.label3); this.tabNotices.Controls.Add(this.cmdRefreshNotices); this.tabNotices.Controls.Add(this.lstNotices); this.tabNotices.Location = new System.Drawing.Point(4, 22); this.tabNotices.Name = "tabNotices"; this.tabNotices.Size = new System.Drawing.Size(409, 481); this.tabNotices.TabIndex = 2; this.tabNotices.Text = "Notices"; this.tabNotices.UseVisualStyleBackColor = true; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(3, 239); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(403, 239); this.textBox1.TabIndex = 18; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(3, 223); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(83, 13); this.label3.TabIndex = 17; this.label3.Text = "Archived Notice"; // // cmdRefreshNotices // this.cmdRefreshNotices.Location = new System.Drawing.Point(289, 194); this.cmdRefreshNotices.Name = "cmdRefreshNotices"; this.cmdRefreshNotices.Size = new System.Drawing.Size(117, 23); this.cmdRefreshNotices.TabIndex = 16; this.cmdRefreshNotices.Text = "Refresh List"; this.cmdRefreshNotices.UseVisualStyleBackColor = true; // // lstNotices // this.lstNotices.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader4, this.columnHeader5, this.columnHeader6}); this.lstNotices.Location = new System.Drawing.Point(3, 8); this.lstNotices.Name = "lstNotices"; this.lstNotices.Size = new System.Drawing.Size(403, 180); this.lstNotices.TabIndex = 15; this.lstNotices.UseCompatibleStateImageBehavior = false; this.lstNotices.View = System.Windows.Forms.View.Details; // // columnHeader4 // this.columnHeader4.Text = "Subject"; this.columnHeader4.Width = 184; // // columnHeader5 // this.columnHeader5.Text = "From"; this.columnHeader5.Width = 125; // // columnHeader6 // this.columnHeader6.Text = "Date"; this.columnHeader6.Width = 87; // // tabProposals // this.tabProposals.Location = new System.Drawing.Point(4, 22); this.tabProposals.Name = "tabProposals"; this.tabProposals.Size = new System.Drawing.Size(409, 481); this.tabProposals.TabIndex = 3; this.tabProposals.Text = "Proposals"; this.tabProposals.UseVisualStyleBackColor = true; // // tabLand // this.tabLand.Controls.Add(this.tabsMoney); this.tabLand.Controls.Add(this.txtContribution); this.tabLand.Controls.Add(this.lblLandAvailable); this.tabLand.Controls.Add(this.lblLandInUse); this.tabLand.Controls.Add(this.lblTotalContribution); this.tabLand.Controls.Add(this.label7); this.tabLand.Controls.Add(this.label6); this.tabLand.Controls.Add(this.label5); this.tabLand.Controls.Add(this.label4); this.tabLand.Controls.Add(this.lstLand); this.tabLand.Location = new System.Drawing.Point(4, 22); this.tabLand.Name = "tabLand"; this.tabLand.Size = new System.Drawing.Size(409, 481); this.tabLand.TabIndex = 4; this.tabLand.Text = "Land & L$"; this.tabLand.UseVisualStyleBackColor = true; // // tabsMoney // this.tabsMoney.Controls.Add(this.tabPlanning); this.tabsMoney.Controls.Add(this.tabDetails); this.tabsMoney.Controls.Add(this.tabSales); this.tabsMoney.Location = new System.Drawing.Point(3, 278); this.tabsMoney.Name = "tabsMoney"; this.tabsMoney.SelectedIndex = 0; this.tabsMoney.Size = new System.Drawing.Size(406, 200); this.tabsMoney.TabIndex = 24; // // tabPlanning // this.tabPlanning.Controls.Add(this.txtPlanning); this.tabPlanning.Location = new System.Drawing.Point(4, 22); this.tabPlanning.Name = "tabPlanning"; this.tabPlanning.Padding = new System.Windows.Forms.Padding(3); this.tabPlanning.Size = new System.Drawing.Size(398, 174); this.tabPlanning.TabIndex = 0; this.tabPlanning.Text = "Planning"; this.tabPlanning.UseVisualStyleBackColor = true; // // txtPlanning // this.txtPlanning.Location = new System.Drawing.Point(6, 5); this.txtPlanning.Multiline = true; this.txtPlanning.Name = "txtPlanning"; this.txtPlanning.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtPlanning.Size = new System.Drawing.Size(386, 163); this.txtPlanning.TabIndex = 13; // // tabDetails // this.tabDetails.Controls.Add(this.txtDetails); this.tabDetails.Location = new System.Drawing.Point(4, 22); this.tabDetails.Name = "tabDetails"; this.tabDetails.Padding = new System.Windows.Forms.Padding(3); this.tabDetails.Size = new System.Drawing.Size(398, 174); this.tabDetails.TabIndex = 1; this.tabDetails.Text = "Details"; this.tabDetails.UseVisualStyleBackColor = true; // // txtDetails // this.txtDetails.Location = new System.Drawing.Point(6, 6); this.txtDetails.Multiline = true; this.txtDetails.Name = "txtDetails"; this.txtDetails.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDetails.Size = new System.Drawing.Size(386, 163); this.txtDetails.TabIndex = 14; // // tabSales // this.tabSales.Controls.Add(this.txtSales); this.tabSales.Location = new System.Drawing.Point(4, 22); this.tabSales.Name = "tabSales"; this.tabSales.Size = new System.Drawing.Size(398, 174); this.tabSales.TabIndex = 2; this.tabSales.Text = "Sales"; this.tabSales.UseVisualStyleBackColor = true; // // txtSales // this.txtSales.Location = new System.Drawing.Point(6, 6); this.txtSales.Multiline = true; this.txtSales.Name = "txtSales"; this.txtSales.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtSales.Size = new System.Drawing.Size(386, 163); this.txtSales.TabIndex = 14; // // txtContribution // this.txtContribution.Location = new System.Drawing.Point(157, 237); this.txtContribution.Name = "txtContribution"; this.txtContribution.Size = new System.Drawing.Size(94, 20); this.txtContribution.TabIndex = 23; // // lblLandAvailable // this.lblLandAvailable.AutoSize = true; this.lblLandAvailable.Location = new System.Drawing.Point(154, 221); this.lblLandAvailable.Name = "lblLandAvailable"; this.lblLandAvailable.Size = new System.Drawing.Size(13, 13); this.lblLandAvailable.TabIndex = 22; this.lblLandAvailable.Text = "0"; // // lblLandInUse // this.lblLandInUse.AutoSize = true; this.lblLandInUse.Location = new System.Drawing.Point(154, 199); this.lblLandInUse.Name = "lblLandInUse"; this.lblLandInUse.Size = new System.Drawing.Size(13, 13); this.lblLandInUse.TabIndex = 21; this.lblLandInUse.Text = "0"; // // lblTotalContribution // this.lblTotalContribution.AutoSize = true; this.lblTotalContribution.Location = new System.Drawing.Point(154, 176); this.lblTotalContribution.Name = "lblTotalContribution"; this.lblTotalContribution.Size = new System.Drawing.Size(13, 13); this.lblTotalContribution.TabIndex = 20; this.lblTotalContribution.Text = "0"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(57, 244); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(91, 13); this.label7.TabIndex = 19; this.label7.Text = "Your Contribution:"; this.label7.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(68, 221); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(80, 13); this.label6.TabIndex = 18; this.label6.Text = "Land Available:"; this.label6.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(53, 199); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(95, 13); this.label5.TabIndex = 17; this.label5.Text = "Total Land In Use:"; this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(55, 176); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(93, 13); this.label4.TabIndex = 16; this.label4.Text = "Total Contribution:"; this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight; // // lstLand // this.lstLand.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader7, this.columnHeader8, this.columnHeader9}); this.lstLand.Location = new System.Drawing.Point(3, 3); this.lstLand.Name = "lstLand"; this.lstLand.Size = new System.Drawing.Size(403, 140); this.lstLand.TabIndex = 15; this.lstLand.UseCompatibleStateImageBehavior = false; this.lstLand.View = System.Windows.Forms.View.Details; // // columnHeader7 // this.columnHeader7.Text = "Parcel Name"; this.columnHeader7.Width = 180; // // columnHeader8 // this.columnHeader8.Text = "Region"; this.columnHeader8.Width = 119; // // columnHeader9 // this.columnHeader9.Text = "Area"; this.columnHeader9.Width = 93; // // cmdApply // this.cmdApply.Location = new System.Drawing.Point(348, 520); this.cmdApply.Name = "cmdApply"; this.cmdApply.Size = new System.Drawing.Size(75, 23); this.cmdApply.TabIndex = 10; this.cmdApply.Text = "Apply"; this.cmdApply.UseVisualStyleBackColor = true; // // cmdCancel // this.cmdCancel.Location = new System.Drawing.Point(267, 520); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.Size = new System.Drawing.Size(75, 23); this.cmdCancel.TabIndex = 11; this.cmdCancel.Text = "Cancel"; this.cmdCancel.UseVisualStyleBackColor = true; // // cmdOK // this.cmdOK.Location = new System.Drawing.Point(186, 520); this.cmdOK.Name = "cmdOK"; this.cmdOK.Size = new System.Drawing.Size(75, 23); this.cmdOK.TabIndex = 12; this.cmdOK.Text = "OK"; this.cmdOK.UseVisualStyleBackColor = true; // // cmdRefresh // this.cmdRefresh.Location = new System.Drawing.Point(6, 520); this.cmdRefresh.Name = "cmdRefresh"; this.cmdRefresh.Size = new System.Drawing.Size(121, 23); this.cmdRefresh.TabIndex = 13; this.cmdRefresh.Text = "Refresh from server"; this.cmdRefresh.UseVisualStyleBackColor = true; // // frmGroupInfo // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(431, 548); this.Controls.Add(this.cmdRefresh); this.Controls.Add(this.cmdOK); this.Controls.Add(this.cmdCancel); this.Controls.Add(this.cmdApply); this.Controls.Add(this.tabs); this.MaximizeBox = false; this.Name = "frmGroupInfo"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "Group Information"; this.tabs.ResumeLayout(false); this.tabGeneral.ResumeLayout(false); this.tabGeneral.PerformLayout(); this.grpPreferences.ResumeLayout(false); this.grpPreferences.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numFee)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picInsignia)).EndInit(); this.tabMembersRoles.ResumeLayout(false); this.tabsMRA.ResumeLayout(false); this.tabMembers.ResumeLayout(false); this.tabMembers.PerformLayout(); this.tabNotices.ResumeLayout(false); this.tabNotices.PerformLayout(); this.tabLand.ResumeLayout(false); this.tabLand.PerformLayout(); this.tabsMoney.ResumeLayout(false); this.tabPlanning.ResumeLayout(false); this.tabPlanning.PerformLayout(); this.tabDetails.ResumeLayout(false); this.tabDetails.PerformLayout(); this.tabSales.ResumeLayout(false); this.tabSales.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabs; private System.Windows.Forms.TabPage tabGeneral; private System.Windows.Forms.GroupBox grpPreferences; private System.Windows.Forms.CheckBox chkMature; private System.Windows.Forms.NumericUpDown numFee; private System.Windows.Forms.CheckBox chkGroupNotices; private System.Windows.Forms.CheckBox chkFee; private System.Windows.Forms.CheckBox chkOpenEnrollment; private System.Windows.Forms.CheckBox chkPublish; private System.Windows.Forms.CheckBox chkShow; private System.Windows.Forms.ListView lstMembers; private System.Windows.Forms.ColumnHeader colName; private System.Windows.Forms.ColumnHeader colTitle; private System.Windows.Forms.ColumnHeader colLasLogin; private System.Windows.Forms.TextBox txtCharter; private System.Windows.Forms.Label lblFoundedBy; private System.Windows.Forms.Label lblGroupName; private System.Windows.Forms.PictureBox picInsignia; private System.Windows.Forms.TabPage tabMembersRoles; private System.Windows.Forms.TabPage tabNotices; private System.Windows.Forms.TabPage tabProposals; private System.Windows.Forms.TabPage tabLand; private System.Windows.Forms.Button cmdApply; private System.Windows.Forms.Button cmdCancel; private System.Windows.Forms.Button cmdOK; private System.Windows.Forms.Button cmdRefresh; private System.Windows.Forms.TabControl tabsMRA; private System.Windows.Forms.TabPage tabMembers; private System.Windows.Forms.TabPage tabRoles; private System.Windows.Forms.TabPage tabAbilities; private System.Windows.Forms.ListView lstMembers2; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.CheckedListBox chkListRoles; private System.Windows.Forms.TreeView treeAbilities; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button cmdEject; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button cmdRefreshNotices; private System.Windows.Forms.ListView lstNotices; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.ListView lstLand; private System.Windows.Forms.ColumnHeader columnHeader7; private System.Windows.Forms.ColumnHeader columnHeader8; private System.Windows.Forms.ColumnHeader columnHeader9; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.TabControl tabsMoney; private System.Windows.Forms.TabPage tabPlanning; private System.Windows.Forms.TabPage tabDetails; private System.Windows.Forms.TextBox txtContribution; private System.Windows.Forms.Label lblLandAvailable; private System.Windows.Forms.Label lblLandInUse; private System.Windows.Forms.Label lblTotalContribution; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtPlanning; private System.Windows.Forms.TextBox txtDetails; private System.Windows.Forms.TabPage tabSales; private System.Windows.Forms.TextBox txtSales; } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using MindTouch.IO; using MindTouch.Tasking; using MindTouch.Web; using MindTouch.Xml; namespace MindTouch.Dream.Http { using Yield = IEnumerator<IYield>; internal class HttpPlugEndpoint : IPlugEndpoint { //--- Types --- internal class ActivityState { //--- Fields --- private object _key = new object(); private Queue<string> _messages = new Queue<string>(); private IDreamEnvironment _env; private string _verb; private string _uri; //--- Constructors --- internal ActivityState(IDreamEnvironment env, string verb, string uri) { _env = env; _verb = verb; _uri = uri; } //--- Messages --- internal void Message(string message) { lock(this) { if(message != null) { if(_messages != null) { _messages.Enqueue(message); if(_messages.Count > 10) { _messages.Dequeue(); } _env.AddActivityDescription(_key, string.Format("Outgoing: {0} {1} [{2}]", _verb, _uri, string.Join(" -> ", _messages.ToArray()))); } } else { _messages = null; _env.RemoveActivityDescription(_key); } } } } //--- Class Fields --- private static log4net.ILog _log = LogUtils.CreateLog(); private static Dictionary<Guid, List<Result<DreamMessage>>> _requests = new Dictionary<Guid, List<Result<DreamMessage>>>(); //--- Class Constructor --- static HttpPlugEndpoint() { #if ALLOW_EXPIRED_HTTPS_CERTS try { ServicePointManager.ServerCertificateValidationCallback = delegate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; } catch(Exception e) { LogUtils.LogError(_log, e, "class ctor"); } #endif } //--- Methods --- public int GetScoreWithNormalizedUri(XUri uri, out XUri normalized) { normalized = uri; switch(uri.Scheme.ToLowerInvariant()) { case "http": case "https": return 1; case "ext-http": normalized = normalized.WithScheme("http"); return int.MaxValue; case "ext-https": normalized = normalized.WithScheme("https"); return int.MaxValue; default: return 0; } } public Yield Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { Result<DreamMessage> res; // register activity DreamContext context = DreamContext.CurrentOrNull; Action<string> activity; if(context != null) { activity = new ActivityState(context.Env, verb, uri.ToString()).Message; } else { activity = delegate(string message) { }; } activity("pre Invoke"); yield return res = Coroutine.Invoke(HandleInvoke, activity, plug, verb, uri, request, new Result<DreamMessage>(response.Timeout)).Catch(); activity("post Invoke"); // unregister activity activity(null); // return response response.Return(res); } private Yield HandleInvoke(Action<string> activity, Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { Result<IAsyncResult> async; // remove internal headers request.Headers.DreamTransport = null; // set request headers request.Headers.Host = uri.Host; if(request.Headers.UserAgent == null) { request.Headers.UserAgent = "Dream/" + DreamUtil.DreamVersion; } // add cookies to request if(request.HasCookies) { request.Headers[DreamHeaders.COOKIE] = DreamCookie.RenderCookieHeader(request.Cookies); } // check if we can pool the request with an existing one if((plug.Credentials == null) && StringUtil.ContainsInvariantIgnoreCase(verb, "GET")) { // create the request hashcode StringBuilder buffer = new StringBuilder(); buffer.AppendLine(uri.ToString()); foreach(KeyValuePair<string, string> header in request.Headers) { buffer.Append(header.Key).Append(": ").Append(header.Value).AppendLine(); } Guid hash = new Guid(StringUtil.ComputeHash(buffer.ToString())); // check if an active connection exists Result<DreamMessage> relay = null; lock(_requests) { List<Result<DreamMessage>> pending; if(_requests.TryGetValue(hash, out pending)) { relay = new Result<DreamMessage>(response.Timeout); pending.Add(relay); } else { pending = new List<Result<DreamMessage>>(); pending.Add(response); _requests[hash] = pending; } } // check if we're pooling a request if(relay != null) { // wait for the relayed response yield return relay; response.Return(relay); yield break; } else { // NOTE (steveb): we use TaskEnv.Instantaneous so that we don't exit the current stack frame before we've executed the continuation; // otherwise, we'll trigger an exception because our result object may not be set. // create new handler to multicast the response to the relays response = new Result<DreamMessage>(response.Timeout, TaskEnv.Instantaneous); response.WhenDone(_ => { List<Result<DreamMessage>> pending; lock(_requests) { _requests.TryGetValue(hash, out pending); _requests.Remove(hash); } // this check should never fail! if(response.HasException) { // send the exception to all relays foreach(Result<DreamMessage> result in pending) { result.Throw(response.Exception); } } else { DreamMessage original = response.Value; // only memorize the message if it needs to be cloned if(pending.Count > 1) { // clone the message to all relays original.Memorize(new Result()).Wait(); foreach(var result in pending) { result.Return(original.Clone()); } } else { // relay the original message pending[0].Return(original); } } }); } } // initialize request activity("pre WebRequest.Create"); var httpRequest = (HttpWebRequest)WebRequest.Create(uri.ToUri()); activity("post WebRequest.Create"); httpRequest.Method = verb; httpRequest.Timeout = System.Threading.Timeout.Infinite; httpRequest.ReadWriteTimeout = System.Threading.Timeout.Infinite; // Note (arnec): httpRequest AutoRedirect is disabled because Plug is responsible for it (this allows redirects to follow // the appropriate handler instead staying stuck in http end point land httpRequest.AllowAutoRedirect = false; // Note from http://support.microsoft.com/kb/904262 // The HTTP request is made up of the following parts: // 1. Sending the request is covered by using the HttpWebRequest.Timeout method. // 2. Getting the response header is covered by using the HttpWebRequest.Timeout method. // 3. Reading the body of the response is not covered by using the HttpWebResponse.Timeout method. In ASP.NET 1.1 and in later versions, reading the body of the response // is covered by using the HttpWebRequest.ReadWriteTimeout method. The HttpWebRequest.ReadWriteTimeout method is used to handle cases where the response headers are // retrieved in a timely manner but where the reading of the response body times out. httpRequest.KeepAlive = false; httpRequest.ProtocolVersion = System.Net.HttpVersion.Version10; // TODO (steveb): set default proxy //httpRequest.Proxy = WebProxy.GetDefaultProxy(); //httpRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; // set credentials if(plug.Credentials != null) { httpRequest.Credentials = plug.Credentials; httpRequest.PreAuthenticate = true; } else if(!string.IsNullOrEmpty(uri.User) || !string.IsNullOrEmpty(uri.Password)) { httpRequest.Credentials = new NetworkCredential(uri.User ?? string.Empty, uri.Password ?? string.Empty); httpRequest.PreAuthenticate = true; // Note (arnec): this manually adds the basic auth header, so it can authorize // in a single request without requiring challenge var authbytes = Encoding.ASCII.GetBytes(string.Concat(uri.User ?? string.Empty, ":", uri.Password ?? string.Empty)); var base64 = Convert.ToBase64String(authbytes); httpRequest.Headers.Add(DreamHeaders.AUTHORIZATION, "Basic " + base64); } // add request headres foreach(KeyValuePair<string, string> header in request.Headers) { HttpUtil.AddHeader(httpRequest, header.Key, header.Value); } // send message stream if((request.ContentLength != 0) || (verb == Verb.POST)) { async = new Result<IAsyncResult>(); try { activity("pre BeginGetRequestStream"); httpRequest.BeginGetRequestStream(async.Return, null); activity("post BeginGetRequestStream"); } catch(Exception e) { activity("pre HandleResponse 1"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetRequestStream", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } activity("pre yield BeginGetRequestStream"); yield return async.Catch(); activity("post yield BeginGetRequestStream"); // send request Stream outStream; try { activity("pre EndGetRequestStream"); outStream = httpRequest.EndGetRequestStream(async.Value); activity("pre EndGetRequestStream"); } catch(Exception e) { activity("pre HandleResponse 2"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetRequestStream", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } // copy data using(outStream) { Result<long> res; activity("pre yield CopyStream"); yield return res = request.ToStream().CopyTo(outStream, request.ContentLength, new Result<long>(TimeSpan.MaxValue)).Catch(); activity("post yield CopyStream"); if(res.HasException) { activity("pre HandleResponse 3"); if(!HandleResponse(activity, res.Exception, null, response)) { _log.ErrorExceptionMethodCall(res.Exception, "HandleInvoke@Async.CopyStream", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } } } request = null; // wait for response async = new Result<IAsyncResult>(response.Timeout); try { activity("pre BeginGetResponse"); httpRequest.BeginGetResponse(async.Return, null); activity("post BeginGetResponse"); } catch(Exception e) { activity("pre HandleResponse 4"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetResponse", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } activity("pre yield BeginGetResponse"); yield return async.Catch(); activity("post yield BeginGetResponse"); // check if an error occurred if(async.HasException) { activity("pre HandleResponse 5"); if(!HandleResponse(activity, async.Exception, null, response)) { _log.ErrorExceptionMethodCall(async.Exception, "HandleInvoke@BeginGetResponse", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } else { // handle response try { HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(async.Value); activity("pre HandleResponse 6"); if(!HandleResponse(activity, null, httpResponse, response)) { try { httpRequest.Abort(); } catch { } } } catch(Exception e) { activity("pre HandleResponse 7"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetResponse", verb, uri); try { httpRequest.Abort(); } catch { } } yield break; } } } private bool HandleResponse(Action<string> activity, Exception exception, HttpWebResponse httpResponse, Result<DreamMessage> response) { if(exception != null) { if(exception is WebException) { activity("pre WebException"); httpResponse = (HttpWebResponse)((WebException)exception).Response; activity("post WebException"); } else { activity("pre HttpWebResponse close"); try { httpResponse.Close(); } catch { } activity("HandleResponse exit 1"); response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception))); return false; } } // check if a response was obtained, otherwise fail if(httpResponse == null) { activity("HandleResponse exit 2"); response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception))); return false; } // determine response type MimeType contentType; Stream stream; HttpStatusCode statusCode = httpResponse.StatusCode; WebHeaderCollection headers = httpResponse.Headers; long contentLength = httpResponse.ContentLength; if(!string.IsNullOrEmpty(httpResponse.ContentType)) { contentType = new MimeType(httpResponse.ContentType); activity("pre new BufferedStream"); stream = new BufferedStream(httpResponse.GetResponseStream()); activity("post new BufferedStream"); } else { // TODO (arnec): If we get a response with a stream, but no content-type, we're currently dropping the stream. Might want to revisit that. _log.DebugFormat("response ({0}) has not content-type and content length of {1}", statusCode, contentLength); contentType = null; stream = Stream.Null; httpResponse.Close(); } // encapsulate the response in a dream message activity("HandleResponse exit 3"); response.Return(new DreamMessage((DreamStatus)(int)statusCode, new DreamHeaders(headers), contentType, contentLength, stream)); return true; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Reflection; using MindTouch.Xml; namespace MindTouch.Dream { internal static class CoreUtil { //--- Constants --- internal const byte PADDING_BYTE = 32; //--- Methods --- internal static XDoc ExecuteCommand(Plug env, DreamHeaders headers, XDoc cmd) { try { switch(cmd.Name.ToLowerInvariant()) { case "script": return ExecuteScript(env, headers, cmd); case "fork": return ExecuteFork(env, headers, cmd); case "action": return ExecuteAction(env, headers, cmd); case "pipe": return ExecutePipe(env, headers, cmd); default: throw new DreamException(string.Format("unregonized script command: " + cmd.Name.ToString())); } } catch(Exception e) { return new XException(e); } } internal static XDoc ExecuteScript(Plug env, DreamHeaders headers, XDoc script) { // execute script commands XDoc reply = new XDoc("results"); string ID = script["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } foreach(XDoc cmd in script.Elements) { reply.Add(ExecuteCommand(env, headers, cmd)); } return reply; } internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork) { // execute script commands XDoc reply = new XDoc("results"); string ID = fork["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } // TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached XDoc forks = fork.Elements; foreach(XDoc cmd in forks) { // TODO (steveb): we should be doing this in parallel, not sequentially! try { reply.Add(ExecuteCommand(env, headers, cmd)); } catch(Exception e) { reply.Add(new XException(e)); } } return reply; } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> internal static XDoc ExecuteAction(Plug env, DreamHeaders headers, XDoc action) { string verb = action["@verb"].Contents; string path = action["@path"].Contents; if((path.Length > 0) && (path[0] == '/')) { path = path.Substring(1); } XUri uri; if(!XUri.TryParse(path, out uri)) { uri = env.Uri.AtAbsolutePath(path); } // create message DreamMessage message = DreamMessage.Ok(GetActionBody(action)); message.Headers.AddRange(headers); // apply headers foreach(XDoc header in action["header"]) { message.Headers[header["@name"].Contents] = header.Contents; } // BUG #814: we need to support events // execute action DreamMessage reply = Plug.New(uri).Invoke(verb, message); // prepare response XDoc result = new XMessage(reply); string ID = action["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { result.Root.Attr("ID", ID); } return result; } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> internal static XDoc ExecutePipe(Plug env, DreamHeaders headers, XDoc pipe) { DreamMessage message = null; foreach(XDoc action in pipe["action"]) { string verb = action["@verb"].Contents; string path = action["@path"].Contents; XUri uri; if(!XUri.TryParse(path, out uri)) { uri = env.Uri.AtPath(path); } // create first message if(message == null) { message = DreamMessage.Ok(GetActionBody(action)); } message.Headers.AddRange(headers); // apply headers foreach(XDoc header in action["header"]) { message.Headers[header["@name"].Contents] = header.Contents; } // execute action message = Plug.New(uri).Invoke(verb, message); if(!message.IsSuccessful) { break; } } // prepare response if(message == null) { return XDoc.Empty; } XDoc result = new XMessage(message); string ID = pipe["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { result.Root.Attr("ID", ID); } return result; } internal static XDoc GetActionBody(XDoc action) { XDoc result = action["body"]; if(!result.IsEmpty) { // check if the body tag contains a nested element if(!result.Elements.IsEmpty) { result = result[0]; } } else { // select the last child element of the <action> element result = action["*[last()]"]; } return result; } internal static Type FindBuiltInTypeBySID(XUri sid) { Assembly assembly = Assembly.GetCallingAssembly(); foreach(Type type in assembly.GetTypes()) { DreamServiceAttribute attr = (DreamServiceAttribute)Attribute.GetCustomAttribute(type, typeof(DreamServiceAttribute), false); XUri[] sids = (attr != null) ? attr.GetSIDAsUris() : new XUri[0]; if(sids.Length > 0) { foreach(XUri tmp in sids) { if(tmp == sid) { return type; } } } } return null; } } }
namespace Lewis.SST.Gui { partial class Main { /// <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(Main)); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.statusBar = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.progressIndicator = new System.Windows.Forms.ToolStripProgressBar(); this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.mainToolbar = new System.Windows.Forms.ToolStrip(); this.btnOpenFile = new System.Windows.Forms.ToolStripSplitButton(); this.sqlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xMLFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.btnSaveFile = new System.Windows.Forms.ToolStripButton(); this.btnSaveAll = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.btnCut = new System.Windows.Forms.ToolStripButton(); this.btnCopy = new System.Windows.Forms.ToolStripButton(); this.btnPaste = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.btnUndo = new System.Windows.Forms.ToolStripButton(); this.btnRedo = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.btnServerExplorer = new System.Windows.Forms.ToolStripButton(); this.btnXmlExplorer = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.btnAbout = new System.Windows.Forms.ToolStripButton(); this.mainMenu = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.xMLFileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.findAndReplaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.findAndReplaceAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.actionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.compareSchemasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.compareXMLSpanshotsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectedDatabasesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xMLSnapshotAndDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateSchemaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.chooseXMLSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectedDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.createServerDTSPackageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xMLFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.compareDataFromToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectedTablesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator(); this.setSecurityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator(); this.getDTSPackageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateXMLOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dTSPackageSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.databaseSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.serverExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xmlExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator(); this.iconsAndTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel(); this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.ActionToolbar = new System.Windows.Forms.ToolStrip(); this.btnSetSecurity = new System.Windows.Forms.ToolStripButton(); this.btnAddServer = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.btnCompareSelected = new System.Windows.Forms.ToolStripSplitButton(); this.createCommandlineBatchFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.btnGenerateSchema = new System.Windows.Forms.ToolStripSplitButton(); this.createCommandToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.btnCreateDTSPackage = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.btnGetDTSPackages = new System.Windows.Forms.ToolStripButton(); this.btnGenXml = new System.Windows.Forms.ToolStripButton(); this.btnGenDatabase = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.btnSyncXml = new System.Windows.Forms.ToolStripButton(); this.btnSelect = new System.Windows.Forms.ToolStripButton(); this.btnRefreshServers = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.btnHTML = new System.Windows.Forms.ToolStripSplitButton(); this.standardViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.statusBar.SuspendLayout(); this.mainToolbar.SuspendLayout(); this.mainMenu.SuspendLayout(); this.toolStripContainer1.BottomToolStripPanel.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.ActionToolbar.SuspendLayout(); this.SuspendLayout(); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "Web_XML.ico"); this.imageList1.Images.SetKeyName(1, "Utility_VBScript.ico"); this.imageList1.Images.SetKeyName(2, "Web_GlobalAppClass.ico"); this.imageList1.Images.SetKeyName(3, "helpdoc.ico"); this.imageList1.Images.SetKeyName(4, "propertiesORoptions.ico"); this.imageList1.Images.SetKeyName(5, "textdoc.ico"); this.imageList1.Images.SetKeyName(6, "document.ico"); this.imageList1.Images.SetKeyName(7, "inifile.ico"); this.imageList1.Images.SetKeyName(8, "rc_html.ico"); this.imageList1.Images.SetKeyName(9, "idr_dll.ico"); this.imageList1.Images.SetKeyName(10, "UtilityText.ico"); this.imageList1.Images.SetKeyName(11, "Web_WebConfig.ico"); this.imageList1.Images.SetKeyName(12, "eventlog.ico"); this.imageList1.Images.SetKeyName(13, "xml.gif"); // // BottomToolStripPanel // this.BottomToolStripPanel.Location = new System.Drawing.Point(0, 0); this.BottomToolStripPanel.Name = "BottomToolStripPanel"; this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.BottomToolStripPanel.Size = new System.Drawing.Size(0, 0); // // statusBar // this.statusBar.Dock = System.Windows.Forms.DockStyle.None; this.statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabel2, this.progressIndicator}); this.statusBar.Location = new System.Drawing.Point(0, 0); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(839, 22); this.statusBar.TabIndex = 3; this.statusBar.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17); this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.MergeAction = System.Windows.Forms.MergeAction.Insert; this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(0, 17); this.toolStripStatusLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // progressIndicator // this.progressIndicator.Name = "progressIndicator"; this.progressIndicator.Size = new System.Drawing.Size(100, 16); // // TopToolStripPanel // this.TopToolStripPanel.Location = new System.Drawing.Point(0, 0); this.TopToolStripPanel.Name = "TopToolStripPanel"; this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.TopToolStripPanel.Size = new System.Drawing.Size(0, 0); // // mainToolbar // this.mainToolbar.AllowItemReorder = true; this.mainToolbar.Dock = System.Windows.Forms.DockStyle.None; this.mainToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnOpenFile, this.btnSaveFile, this.btnSaveAll, this.toolStripSeparator1, this.btnCut, this.btnCopy, this.btnPaste, this.toolStripSeparator2, this.btnUndo, this.btnRedo, this.toolStripSeparator3, this.btnServerExplorer, this.btnXmlExplorer, this.toolStripSeparator4, this.btnAbout}); this.mainToolbar.Location = new System.Drawing.Point(3, 24); this.mainToolbar.Name = "mainToolbar"; this.mainToolbar.Size = new System.Drawing.Size(298, 25); this.mainToolbar.TabIndex = 2; this.mainToolbar.Text = "Toolbar Buttons"; // // btnOpenFile // this.btnOpenFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnOpenFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sqlToolStripMenuItem, this.xMLFilesToolStripMenuItem}); this.btnOpenFile.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenFile.Image"))); this.btnOpenFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnOpenFile.Name = "btnOpenFile"; this.btnOpenFile.Size = new System.Drawing.Size(32, 22); this.btnOpenFile.Text = "Open Files..."; this.btnOpenFile.ButtonClick += new System.EventHandler(this.btnOpenFile_ButtonClick); // // sqlToolStripMenuItem // this.sqlToolStripMenuItem.Name = "sqlToolStripMenuItem"; this.sqlToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.sqlToolStripMenuItem.Text = "SQL File..."; this.sqlToolStripMenuItem.Click += new System.EventHandler(this.sqlToolStripMenuItem_Click); // // xMLFilesToolStripMenuItem // this.xMLFilesToolStripMenuItem.Name = "xMLFilesToolStripMenuItem"; this.xMLFilesToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.xMLFilesToolStripMenuItem.Text = "XML File..."; this.xMLFilesToolStripMenuItem.Click += new System.EventHandler(this.xMLFilesToolStripMenuItem_Click); // // btnSaveFile // this.btnSaveFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSaveFile.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveFile.Image"))); this.btnSaveFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSaveFile.Name = "btnSaveFile"; this.btnSaveFile.Size = new System.Drawing.Size(23, 22); this.btnSaveFile.Text = "Save Current Open Document"; this.btnSaveFile.Click += new System.EventHandler(this.btnSaveFile_Click); // // btnSaveAll // this.btnSaveAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSaveAll.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAll.Image"))); this.btnSaveAll.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSaveAll.Name = "btnSaveAll"; this.btnSaveAll.Size = new System.Drawing.Size(23, 22); this.btnSaveAll.Text = "Save All Open Documents"; this.btnSaveAll.Click += new System.EventHandler(this.btnSaveAll_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // btnCut // this.btnCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnCut.Image = ((System.Drawing.Image)(resources.GetObject("btnCut.Image"))); this.btnCut.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnCut.Name = "btnCut"; this.btnCut.Size = new System.Drawing.Size(23, 22); this.btnCut.Text = "Cut selected text"; this.btnCut.Click += new System.EventHandler(this.btnCut_Click); // // btnCopy // this.btnCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnCopy.Image = ((System.Drawing.Image)(resources.GetObject("btnCopy.Image"))); this.btnCopy.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnCopy.Name = "btnCopy"; this.btnCopy.Size = new System.Drawing.Size(23, 22); this.btnCopy.Text = "Copy selected text"; this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click); // // btnPaste // this.btnPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnPaste.Enabled = false; this.btnPaste.Image = ((System.Drawing.Image)(resources.GetObject("btnPaste.Image"))); this.btnPaste.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnPaste.Name = "btnPaste"; this.btnPaste.Size = new System.Drawing.Size(23, 22); this.btnPaste.Text = "Paste saved text"; this.btnPaste.Click += new System.EventHandler(this.btnPaste_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // btnUndo // this.btnUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnUndo.Image = ((System.Drawing.Image)(resources.GetObject("btnUndo.Image"))); this.btnUndo.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnUndo.Name = "btnUndo"; this.btnUndo.Size = new System.Drawing.Size(23, 22); this.btnUndo.Text = "Undo edit"; this.btnUndo.Click += new System.EventHandler(this.btnUndo_Click); // // btnRedo // this.btnRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnRedo.Enabled = false; this.btnRedo.Image = ((System.Drawing.Image)(resources.GetObject("btnRedo.Image"))); this.btnRedo.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnRedo.Name = "btnRedo"; this.btnRedo.Size = new System.Drawing.Size(23, 22); this.btnRedo.Text = "Redo edit"; this.btnRedo.Click += new System.EventHandler(this.btnRedo_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // btnServerExplorer // this.btnServerExplorer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnServerExplorer.Image = ((System.Drawing.Image)(resources.GetObject("btnServerExplorer.Image"))); this.btnServerExplorer.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnServerExplorer.Name = "btnServerExplorer"; this.btnServerExplorer.Size = new System.Drawing.Size(23, 22); this.btnServerExplorer.Text = "Display Server Explorer"; this.btnServerExplorer.Click += new System.EventHandler(this.btnServerExplorer_Click); // // btnXmlExplorer // this.btnXmlExplorer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnXmlExplorer.Image = ((System.Drawing.Image)(resources.GetObject("btnXmlExplorer.Image"))); this.btnXmlExplorer.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnXmlExplorer.Name = "btnXmlExplorer"; this.btnXmlExplorer.Size = new System.Drawing.Size(23, 22); this.btnXmlExplorer.Text = "Display XML Explorer"; this.btnXmlExplorer.Click += new System.EventHandler(this.btnXmlExplorer_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // btnAbout // this.btnAbout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnAbout.Image = ((System.Drawing.Image)(resources.GetObject("btnAbout.Image"))); this.btnAbout.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnAbout.Name = "btnAbout"; this.btnAbout.Size = new System.Drawing.Size(23, 22); this.btnAbout.Text = "Show About Window"; this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); // // mainMenu // this.mainMenu.Dock = System.Windows.Forms.DockStyle.None; this.mainMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible; this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.actionToolStripMenuItem, this.viewToolStripMenuItem, this.windowToolStripMenuItem, this.helpToolStripMenuItem}); this.mainMenu.Location = new System.Drawing.Point(0, 0); this.mainMenu.Name = "mainMenu"; this.mainMenu.Size = new System.Drawing.Size(839, 24); this.mainMenu.TabIndex = 4; this.mainMenu.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.saveAllToolStripMenuItem, this.toolStripMenuItem1, this.closeToolStripMenuItem, this.closeAllToolStripMenuItem, this.toolStripMenuItem3, this.printToolStripMenuItem, this.toolStripMenuItem6, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // openToolStripMenuItem // this.openToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem1, this.xMLFileToolStripMenuItem1}); this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.openToolStripMenuItem.Text = "&Open"; // // fileToolStripMenuItem1 // this.fileToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("fileToolStripMenuItem1.Image"))); this.fileToolStripMenuItem1.Name = "fileToolStripMenuItem1"; this.fileToolStripMenuItem1.Size = new System.Drawing.Size(135, 22); this.fileToolStripMenuItem1.Text = "&SQL File..."; this.fileToolStripMenuItem1.Click += new System.EventHandler(this.fileToolStripMenuItem1_Click); // // xMLFileToolStripMenuItem1 // this.xMLFileToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("xMLFileToolStripMenuItem1.Image"))); this.xMLFileToolStripMenuItem1.Name = "xMLFileToolStripMenuItem1"; this.xMLFileToolStripMenuItem1.Size = new System.Drawing.Size(135, 22); this.xMLFileToolStripMenuItem1.Text = "&XML File..."; this.xMLFileToolStripMenuItem1.Click += new System.EventHandler(this.xMLFileToolStripMenuItem1_Click); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.saveToolStripMenuItem.Text = "&Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.saveAsToolStripMenuItem.Text = "Save &As..."; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); // // saveAllToolStripMenuItem // this.saveAllToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveAllToolStripMenuItem.Image"))); this.saveAllToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black; this.saveAllToolStripMenuItem.Name = "saveAllToolStripMenuItem"; this.saveAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.saveAllToolStripMenuItem.Text = "Save A&ll"; this.saveAllToolStripMenuItem.Click += new System.EventHandler(this.saveAllToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(133, 6); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; this.closeToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.closeToolStripMenuItem.Text = "&Close"; this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click); // // closeAllToolStripMenuItem // this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem"; this.closeAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.closeAllToolStripMenuItem.Text = "Clos&e All"; this.closeAllToolStripMenuItem.Click += new System.EventHandler(this.closeAllToolStripMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(133, 6); // // printToolStripMenuItem // this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image"))); this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.printToolStripMenuItem.Text = "&Print"; this.printToolStripMenuItem.Visible = false; this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click); // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; this.toolStripMenuItem6.Size = new System.Drawing.Size(133, 6); this.toolStripMenuItem6.Visible = false; // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem, this.toolStripMenuItem5, this.cutToolStripMenuItem, this.copyToolStripMenuItem, this.pasteToolStripMenuItem, this.toolStripMenuItem4, this.findToolStripMenuItem, this.findAndReplaceToolStripMenuItem, this.findAndReplaceAllToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.editToolStripMenuItem.Text = "&Edit"; // // undoToolStripMenuItem // this.undoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("undoToolStripMenuItem.Image"))); this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; this.undoToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.undoToolStripMenuItem.Text = "Un&do"; this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Enabled = false; this.redoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("redoToolStripMenuItem.Image"))); this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; this.redoToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.redoToolStripMenuItem.Text = "R&edo"; this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(178, 6); // // cutToolStripMenuItem // this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image"))); this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; this.cutToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.cutToolStripMenuItem.Text = "C&ut"; this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image"))); this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.copyToolStripMenuItem.Text = "&Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Enabled = false; this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image"))); this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; this.pasteToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.pasteToolStripMenuItem.Text = "&Paste"; this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(178, 6); // // findToolStripMenuItem // this.findToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("findToolStripMenuItem.Image"))); this.findToolStripMenuItem.Name = "findToolStripMenuItem"; this.findToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.findToolStripMenuItem.Text = "&Find"; this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click); // // findAndReplaceToolStripMenuItem // this.findAndReplaceToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("findAndReplaceToolStripMenuItem.Image"))); this.findAndReplaceToolStripMenuItem.Name = "findAndReplaceToolStripMenuItem"; this.findAndReplaceToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.findAndReplaceToolStripMenuItem.Text = "Find and &Replace"; this.findAndReplaceToolStripMenuItem.Click += new System.EventHandler(this.findAndReplaceToolStripMenuItem_Click); // // findAndReplaceAllToolStripMenuItem // this.findAndReplaceAllToolStripMenuItem.Name = "findAndReplaceAllToolStripMenuItem"; this.findAndReplaceAllToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.findAndReplaceAllToolStripMenuItem.Text = "Find and Replace &All"; this.findAndReplaceAllToolStripMenuItem.Click += new System.EventHandler(this.findAndReplaceAllToolStripMenuItem_Click); // // actionToolStripMenuItem // this.actionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.compareSchemasToolStripMenuItem, this.generateSchemaToolStripMenuItem, this.createServerDTSPackageToolStripMenuItem, this.toolStripMenuItem2, this.compareDataFromToolStripMenuItem, this.toolStripMenuItem8, this.setSecurityToolStripMenuItem, this.addServerToolStripMenuItem, this.toolStripMenuItem7, this.getDTSPackageToolStripMenuItem, this.generateXMLOutputToolStripMenuItem}); this.actionToolStripMenuItem.Name = "actionToolStripMenuItem"; this.actionToolStripMenuItem.Size = new System.Drawing.Size(49, 20); this.actionToolStripMenuItem.Text = "&Action"; // // compareSchemasToolStripMenuItem // this.compareSchemasToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.compareXMLSpanshotsToolStripMenuItem, this.selectedDatabasesToolStripMenuItem, this.xMLSnapshotAndDatabaseToolStripMenuItem}); this.compareSchemasToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("compareSchemasToolStripMenuItem.Image"))); this.compareSchemasToolStripMenuItem.Name = "compareSchemasToolStripMenuItem"; this.compareSchemasToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.compareSchemasToolStripMenuItem.Text = "&Compare Schemas From..."; // // compareXMLSpanshotsToolStripMenuItem // this.compareXMLSpanshotsToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.compareXMLSpanshotsToolStripMenuItem.Name = "compareXMLSpanshotsToolStripMenuItem"; this.compareXMLSpanshotsToolStripMenuItem.Size = new System.Drawing.Size(222, 22); this.compareXMLSpanshotsToolStripMenuItem.Text = "&XML Snapshots"; this.compareXMLSpanshotsToolStripMenuItem.Click += new System.EventHandler(this.compareXMLSpanshotsToolStripMenuItem_Click); // // selectedDatabasesToolStripMenuItem // this.selectedDatabasesToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.selectedDatabasesToolStripMenuItem.Enabled = false; this.selectedDatabasesToolStripMenuItem.Name = "selectedDatabasesToolStripMenuItem"; this.selectedDatabasesToolStripMenuItem.Size = new System.Drawing.Size(222, 22); this.selectedDatabasesToolStripMenuItem.Text = "Selected &Databases"; this.selectedDatabasesToolStripMenuItem.Click += new System.EventHandler(this.selectedDatabasesToolStripMenuItem_Click); // // xMLSnapshotAndDatabaseToolStripMenuItem // this.xMLSnapshotAndDatabaseToolStripMenuItem.Enabled = false; this.xMLSnapshotAndDatabaseToolStripMenuItem.Name = "xMLSnapshotAndDatabaseToolStripMenuItem"; this.xMLSnapshotAndDatabaseToolStripMenuItem.Size = new System.Drawing.Size(222, 22); this.xMLSnapshotAndDatabaseToolStripMenuItem.Text = "XML &Snapshot and Database"; this.xMLSnapshotAndDatabaseToolStripMenuItem.Click += new System.EventHandler(this.xMLSnapshotAndDatabaseToolStripMenuItem_Click); // // generateSchemaToolStripMenuItem // this.generateSchemaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.chooseXMLSnapshotToolStripMenuItem, this.selectedDatabaseToolStripMenuItem}); this.generateSchemaToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("generateSchemaToolStripMenuItem.Image"))); this.generateSchemaToolStripMenuItem.Name = "generateSchemaToolStripMenuItem"; this.generateSchemaToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.generateSchemaToolStripMenuItem.Text = "&Generate SQL Schema From..."; // // chooseXMLSnapshotToolStripMenuItem // this.chooseXMLSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.chooseXMLSnapshotToolStripMenuItem.Name = "chooseXMLSnapshotToolStripMenuItem"; this.chooseXMLSnapshotToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.chooseXMLSnapshotToolStripMenuItem.Text = "&XML Snapshot"; this.chooseXMLSnapshotToolStripMenuItem.Click += new System.EventHandler(this.chooseXMLSnapshotToolStripMenuItem_Click); // // selectedDatabaseToolStripMenuItem // this.selectedDatabaseToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.selectedDatabaseToolStripMenuItem.Enabled = false; this.selectedDatabaseToolStripMenuItem.Name = "selectedDatabaseToolStripMenuItem"; this.selectedDatabaseToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.selectedDatabaseToolStripMenuItem.Text = "Selected &Database"; this.selectedDatabaseToolStripMenuItem.Click += new System.EventHandler(this.selectedDatabaseToolStripMenuItem_Click); // // createServerDTSPackageToolStripMenuItem // this.createServerDTSPackageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.xMLFileToolStripMenuItem}); this.createServerDTSPackageToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("createServerDTSPackageToolStripMenuItem.Image"))); this.createServerDTSPackageToolStripMenuItem.Name = "createServerDTSPackageToolStripMenuItem"; this.createServerDTSPackageToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.createServerDTSPackageToolStripMenuItem.Text = "&Recreate DTS Package From..."; // // xMLFileToolStripMenuItem // this.xMLFileToolStripMenuItem.Name = "xMLFileToolStripMenuItem"; this.xMLFileToolStripMenuItem.Size = new System.Drawing.Size(147, 22); this.xMLFileToolStripMenuItem.Text = "XML &Package"; this.xMLFileToolStripMenuItem.Click += new System.EventHandler(this.xMLFileToolStripMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(230, 6); // // compareDataFromToolStripMenuItem // this.compareDataFromToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.selectedTablesMenuItem}); this.compareDataFromToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("compareDataFromToolStripMenuItem.Image"))); this.compareDataFromToolStripMenuItem.Name = "compareDataFromToolStripMenuItem"; this.compareDataFromToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.compareDataFromToolStripMenuItem.Text = "Compare Data &From..."; // // selectedTablesMenuItem // this.selectedTablesMenuItem.Enabled = false; this.selectedTablesMenuItem.Name = "selectedTablesMenuItem"; this.selectedTablesMenuItem.Size = new System.Drawing.Size(160, 22); this.selectedTablesMenuItem.Text = "&Selected Tables"; this.selectedTablesMenuItem.Click += new System.EventHandler(this.selectedTablesToolStripMenuItem_Click); // // toolStripMenuItem8 // this.toolStripMenuItem8.Name = "toolStripMenuItem8"; this.toolStripMenuItem8.Size = new System.Drawing.Size(230, 6); // // setSecurityToolStripMenuItem // this.setSecurityToolStripMenuItem.Enabled = false; this.setSecurityToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("setSecurityToolStripMenuItem.Image"))); this.setSecurityToolStripMenuItem.Name = "setSecurityToolStripMenuItem"; this.setSecurityToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.setSecurityToolStripMenuItem.Text = "&Set Server Security"; this.setSecurityToolStripMenuItem.Click += new System.EventHandler(this.setSecurityToolStripMenuItem_Click); // // addServerToolStripMenuItem // this.addServerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addServerToolStripMenuItem.Image"))); this.addServerToolStripMenuItem.Name = "addServerToolStripMenuItem"; this.addServerToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.addServerToolStripMenuItem.Text = "&Add SQL Server Login"; this.addServerToolStripMenuItem.Click += new System.EventHandler(this.addServerToolStripMenuItem_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(230, 6); // // getDTSPackageToolStripMenuItem // this.getDTSPackageToolStripMenuItem.Enabled = false; this.getDTSPackageToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("getDTSPackageToolStripMenuItem.Image"))); this.getDTSPackageToolStripMenuItem.Name = "getDTSPackageToolStripMenuItem"; this.getDTSPackageToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.getDTSPackageToolStripMenuItem.Text = "Get Server &DTS Packages"; this.getDTSPackageToolStripMenuItem.Click += new System.EventHandler(this.getDTSPackageToolStripMenuItem_Click); // // generateXMLOutputToolStripMenuItem // this.generateXMLOutputToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.dTSPackageSnapshotToolStripMenuItem, this.databaseSnapshotToolStripMenuItem}); this.generateXMLOutputToolStripMenuItem.Enabled = false; this.generateXMLOutputToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("generateXMLOutputToolStripMenuItem.Image"))); this.generateXMLOutputToolStripMenuItem.Name = "generateXMLOutputToolStripMenuItem"; this.generateXMLOutputToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.generateXMLOutputToolStripMenuItem.Text = "Generate &XML From..."; // // dTSPackageSnapshotToolStripMenuItem // this.dTSPackageSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.dTSPackageSnapshotToolStripMenuItem.Enabled = false; this.dTSPackageSnapshotToolStripMenuItem.Name = "dTSPackageSnapshotToolStripMenuItem"; this.dTSPackageSnapshotToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.dTSPackageSnapshotToolStripMenuItem.Text = "&Selected DTS Package"; this.dTSPackageSnapshotToolStripMenuItem.Click += new System.EventHandler(this.dTSPackageSnapshotToolStripMenuItem_Click); // // databaseSnapshotToolStripMenuItem // this.databaseSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.databaseSnapshotToolStripMenuItem.Enabled = false; this.databaseSnapshotToolStripMenuItem.Name = "databaseSnapshotToolStripMenuItem"; this.databaseSnapshotToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.databaseSnapshotToolStripMenuItem.Text = "Selected &Database"; this.databaseSnapshotToolStripMenuItem.Click += new System.EventHandler(this.databaseSnapshotToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.serverExplorerToolStripMenuItem, this.xmlExplorerToolStripMenuItem, this.toolStripMenuItem9, this.iconsAndTextToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20); this.viewToolStripMenuItem.Text = "&View"; // // serverExplorerToolStripMenuItem // this.serverExplorerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("serverExplorerToolStripMenuItem.Image"))); this.serverExplorerToolStripMenuItem.Name = "serverExplorerToolStripMenuItem"; this.serverExplorerToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.serverExplorerToolStripMenuItem.Text = "&Server Explorer"; this.serverExplorerToolStripMenuItem.Click += new System.EventHandler(this.serverExplorerToolStripMenuItem_Click); // // xmlExplorerToolStripMenuItem // this.xmlExplorerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("xmlExplorerToolStripMenuItem.Image"))); this.xmlExplorerToolStripMenuItem.Name = "xmlExplorerToolStripMenuItem"; this.xmlExplorerToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.xmlExplorerToolStripMenuItem.Text = "&XML Explorer"; this.xmlExplorerToolStripMenuItem.Click += new System.EventHandler(this.xmlExplorerToolStripMenuItem_Click); // // toolStripMenuItem9 // this.toolStripMenuItem9.Name = "toolStripMenuItem9"; this.toolStripMenuItem9.Size = new System.Drawing.Size(189, 6); // // iconsAndTextToolStripMenuItem // this.iconsAndTextToolStripMenuItem.CheckOnClick = true; this.iconsAndTextToolStripMenuItem.Name = "iconsAndTextToolStripMenuItem"; this.iconsAndTextToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.iconsAndTextToolStripMenuItem.Text = "Button Icons and Text"; this.iconsAndTextToolStripMenuItem.Click += new System.EventHandler(this.iconsAndTextToolStripMenuItem_Click); // // windowToolStripMenuItem // this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsToolStripMenuItem}); this.windowToolStripMenuItem.Name = "windowToolStripMenuItem"; this.windowToolStripMenuItem.Size = new System.Drawing.Size(57, 20); this.windowToolStripMenuItem.Text = "&Window"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(122, 22); this.optionsToolStripMenuItem.Text = "&Options"; this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("aboutToolStripMenuItem.Image"))); this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(199, 22); this.aboutToolStripMenuItem.Text = "&About SQL Schema Tool"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // RightToolStripPanel // this.RightToolStripPanel.Location = new System.Drawing.Point(0, 0); this.RightToolStripPanel.Name = "RightToolStripPanel"; this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.RightToolStripPanel.Size = new System.Drawing.Size(0, 0); // // LeftToolStripPanel // this.LeftToolStripPanel.Location = new System.Drawing.Point(0, 0); this.LeftToolStripPanel.Name = "LeftToolStripPanel"; this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.LeftToolStripPanel.Size = new System.Drawing.Size(0, 0); // // ContentPanel // this.ContentPanel.AutoScroll = true; this.ContentPanel.Size = new System.Drawing.Size(551, 378); // // dockPanel // this.dockPanel.ActiveAutoHideContent = null; this.dockPanel.AllowEndUserNestedDocking = false; this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingWindow; this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World); this.dockPanel.Location = new System.Drawing.Point(0, 0); this.dockPanel.Name = "dockPanel"; this.dockPanel.Size = new System.Drawing.Size(839, 378); this.dockPanel.TabIndex = 8; // // toolStripContainer1 // // // toolStripContainer1.BottomToolStripPanel // this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this.statusBar); // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.AutoScroll = true; this.toolStripContainer1.ContentPanel.Controls.Add(this.dockPanel); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(839, 378); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(839, 449); this.toolStripContainer1.TabIndex = 9; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.mainMenu); this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.mainToolbar); this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.ActionToolbar); // // ActionToolbar // this.ActionToolbar.Dock = System.Windows.Forms.DockStyle.None; this.ActionToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnSetSecurity, this.btnAddServer, this.toolStripSeparator5, this.btnCompareSelected, this.btnGenerateSchema, this.btnCreateDTSPackage, this.toolStripSeparator6, this.btnGetDTSPackages, this.btnGenXml, this.btnGenDatabase, this.toolStripSeparator7, this.btnSyncXml, this.btnSelect, this.btnRefreshServers, this.toolStripSeparator8, this.btnHTML}); this.ActionToolbar.Location = new System.Drawing.Point(301, 24); this.ActionToolbar.Name = "ActionToolbar"; this.ActionToolbar.Size = new System.Drawing.Size(339, 25); this.ActionToolbar.TabIndex = 5; // // btnSetSecurity // this.btnSetSecurity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSetSecurity.Enabled = false; this.btnSetSecurity.Image = ((System.Drawing.Image)(resources.GetObject("btnSetSecurity.Image"))); this.btnSetSecurity.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSetSecurity.Name = "btnSetSecurity"; this.btnSetSecurity.Size = new System.Drawing.Size(23, 22); this.btnSetSecurity.Text = "Server Security Settings"; this.btnSetSecurity.Click += new System.EventHandler(this.btnSetSecurity_Click); // // btnAddServer // this.btnAddServer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnAddServer.Image = ((System.Drawing.Image)(resources.GetObject("btnAddServer.Image"))); this.btnAddServer.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnAddServer.Name = "btnAddServer"; this.btnAddServer.Size = new System.Drawing.Size(23, 22); this.btnAddServer.Text = "Add SQL Server Login"; this.btnAddServer.Click += new System.EventHandler(this.btnAddServer_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // btnCompareSelected // this.btnCompareSelected.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnCompareSelected.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.createCommandlineBatchFileToolStripMenuItem}); this.btnCompareSelected.Image = ((System.Drawing.Image)(resources.GetObject("btnCompareSelected.Image"))); this.btnCompareSelected.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnCompareSelected.Name = "btnCompareSelected"; this.btnCompareSelected.Size = new System.Drawing.Size(32, 22); this.btnCompareSelected.Text = "Compare Selected Objects..."; this.btnCompareSelected.ToolTipText = "Compare Selected..."; this.btnCompareSelected.ButtonClick += new System.EventHandler(this.btnCompareSelected_Click); // // createCommandlineBatchFileToolStripMenuItem // this.createCommandlineBatchFileToolStripMenuItem.Name = "createCommandlineBatchFileToolStripMenuItem"; this.createCommandlineBatchFileToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.createCommandlineBatchFileToolStripMenuItem.Text = "Create Commandline Batch File"; this.createCommandlineBatchFileToolStripMenuItem.Click += new System.EventHandler(this.createCommandlineBatchFileToolStripMenuItem_Click); // // btnGenerateSchema // this.btnGenerateSchema.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnGenerateSchema.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.createCommandToolStripMenuItem}); this.btnGenerateSchema.Image = ((System.Drawing.Image)(resources.GetObject("btnGenerateSchema.Image"))); this.btnGenerateSchema.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnGenerateSchema.Name = "btnGenerateSchema"; this.btnGenerateSchema.Size = new System.Drawing.Size(32, 22); this.btnGenerateSchema.Text = "Generate SQL Schema From..."; this.btnGenerateSchema.ToolTipText = "Generate SQL Schema From Selected..."; this.btnGenerateSchema.ButtonClick += new System.EventHandler(this.btnGenerateSchema_Click); // // createCommandToolStripMenuItem // this.createCommandToolStripMenuItem.Name = "createCommandToolStripMenuItem"; this.createCommandToolStripMenuItem.Size = new System.Drawing.Size(233, 22); this.createCommandToolStripMenuItem.Text = "Create Commandline Batch File"; this.createCommandToolStripMenuItem.Click += new System.EventHandler(this.createCommandToolStripMenuItem_Click); // // btnCreateDTSPackage // this.btnCreateDTSPackage.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnCreateDTSPackage.Image = ((System.Drawing.Image)(resources.GetObject("btnCreateDTSPackage.Image"))); this.btnCreateDTSPackage.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnCreateDTSPackage.Name = "btnCreateDTSPackage"; this.btnCreateDTSPackage.Size = new System.Drawing.Size(23, 22); this.btnCreateDTSPackage.Text = "Recreate DTS Package From..."; this.btnCreateDTSPackage.ToolTipText = "Recreate DTS Package From Selected..."; this.btnCreateDTSPackage.Click += new System.EventHandler(this.btnCreateDTSPackage_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // btnGetDTSPackages // this.btnGetDTSPackages.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnGetDTSPackages.Enabled = false; this.btnGetDTSPackages.Image = ((System.Drawing.Image)(resources.GetObject("btnGetDTSPackages.Image"))); this.btnGetDTSPackages.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnGetDTSPackages.Name = "btnGetDTSPackages"; this.btnGetDTSPackages.Size = new System.Drawing.Size(23, 22); this.btnGetDTSPackages.Text = "Get Server DTS Packages"; this.btnGetDTSPackages.Click += new System.EventHandler(this.getDTSPackages_Click); // // btnGenXml // this.btnGenXml.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnGenXml.Enabled = false; this.btnGenXml.Image = ((System.Drawing.Image)(resources.GetObject("btnGenXml.Image"))); this.btnGenXml.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnGenXml.Name = "btnGenXml"; this.btnGenXml.Size = new System.Drawing.Size(23, 22); this.btnGenXml.Text = "Generate XML From..."; this.btnGenXml.ToolTipText = "Generate XML From Selected..."; this.btnGenXml.Click += new System.EventHandler(this.btnGenXml_Click); // // btnGenDatabase // this.btnGenDatabase.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnGenDatabase.Enabled = false; this.btnGenDatabase.Image = ((System.Drawing.Image)(resources.GetObject("btnGenDatabase.Image"))); this.btnGenDatabase.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnGenDatabase.Name = "btnGenDatabase"; this.btnGenDatabase.Size = new System.Drawing.Size(23, 22); this.btnGenDatabase.Text = "Execute SQL Doc"; this.btnGenDatabase.ToolTipText = "Execute SQL Doc as a command on a server database"; this.btnGenDatabase.Click += new System.EventHandler(this.btnGenDatabase_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // btnSyncXml // this.btnSyncXml.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSyncXml.Enabled = false; this.btnSyncXml.Image = ((System.Drawing.Image)(resources.GetObject("btnSyncXml.Image"))); this.btnSyncXml.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSyncXml.Name = "btnSyncXml"; this.btnSyncXml.Size = new System.Drawing.Size(23, 22); this.btnSyncXml.Text = "Sync with XML Node Explorer"; this.btnSyncXml.Click += new System.EventHandler(this.btnSyncXml_Click); // // btnSelect // this.btnSelect.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSelect.Enabled = false; this.btnSelect.Image = ((System.Drawing.Image)(resources.GetObject("btnSelect.Image"))); this.btnSelect.ImageTransparentColor = System.Drawing.Color.Transparent; this.btnSelect.Name = "btnSelect"; this.btnSelect.Size = new System.Drawing.Size(23, 22); this.btnSelect.Text = "Select For Compare"; this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click); // // btnRefreshServers // this.btnRefreshServers.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnRefreshServers.Enabled = false; this.btnRefreshServers.Image = ((System.Drawing.Image)(resources.GetObject("btnRefreshServers.Image"))); this.btnRefreshServers.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnRefreshServers.Name = "btnRefreshServers"; this.btnRefreshServers.Size = new System.Drawing.Size(23, 22); this.btnRefreshServers.Text = "Refresh Servers"; this.btnRefreshServers.ToolTipText = "Refresh SQL server list from the available local and networked SQL servers"; this.btnRefreshServers.Click += new System.EventHandler(this.btnRefreshServers_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // btnHTML // this.btnHTML.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnHTML.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.standardViewToolStripMenuItem}); this.btnHTML.Enabled = false; this.btnHTML.Image = ((System.Drawing.Image)(resources.GetObject("btnHTML.Image"))); this.btnHTML.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnHTML.Name = "btnHTML"; this.btnHTML.Size = new System.Drawing.Size(32, 22); this.btnHTML.Text = "Display HTML Report"; this.btnHTML.ButtonClick += new System.EventHandler(this.btnHTML_Click); // // standardViewToolStripMenuItem // this.standardViewToolStripMenuItem.Name = "standardViewToolStripMenuItem"; this.standardViewToolStripMenuItem.Size = new System.Drawing.Size(190, 22); this.standardViewToolStripMenuItem.Text = "Standard Report View"; this.standardViewToolStripMenuItem.ToolTipText = "Standard Browser XML View"; this.standardViewToolStripMenuItem.Click += new System.EventHandler(this.standardViewToolStripMenuItem_Click); // // timer1 // this.timer1.Interval = 1000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Main // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(839, 449); this.Controls.Add(this.toolStripContainer1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.MainMenuStrip = this.mainMenu; this.Name = "Main"; this.Text = "SQL Schema Tool"; this.Load += new System.EventHandler(this.Main_Load); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing); this.statusBar.ResumeLayout(false); this.statusBar.PerformLayout(); this.mainToolbar.ResumeLayout(false); this.mainToolbar.PerformLayout(); this.mainMenu.ResumeLayout(false); this.mainMenu.PerformLayout(); this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false); this.toolStripContainer1.BottomToolStripPanel.PerformLayout(); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.ActionToolbar.ResumeLayout(false); this.ActionToolbar.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.StatusStrip statusBar; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; private System.Windows.Forms.ToolStrip mainToolbar; private System.Windows.Forms.ToolStripSplitButton btnOpenFile; private System.Windows.Forms.ToolStripMenuItem sqlToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem xMLFilesToolStripMenuItem; private System.Windows.Forms.ToolStripButton btnSaveFile; private System.Windows.Forms.ToolStripButton btnSaveAll; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton btnCut; private System.Windows.Forms.ToolStripButton btnCopy; private System.Windows.Forms.ToolStripButton btnPaste; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton btnUndo; private System.Windows.Forms.ToolStripButton btnRedo; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton btnServerExplorer; private System.Windows.Forms.ToolStripButton btnXmlExplorer; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripButton btnAbout; private System.Windows.Forms.MenuStrip mainMenu; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem xMLFileToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAllToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem closeAllToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem findAndReplaceToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem findAndReplaceAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem actionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem compareSchemasToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem compareXMLSpanshotsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectedDatabasesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem xMLSnapshotAndDatabaseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem generateSchemaToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem chooseXMLSnapshotToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectedDatabaseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem createServerDTSPackageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem xMLFileToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem setSecurityToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addServerToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem getDTSPackageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem generateXMLOutputToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem dTSPackageSnapshotToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem databaseSnapshotToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem serverExplorerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem xmlExplorerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ToolStrip ActionToolbar; private System.Windows.Forms.ToolStripButton btnSetSecurity; private System.Windows.Forms.ToolStripButton btnAddServer; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripButton btnGetDTSPackages; private System.Windows.Forms.ToolStripButton btnGenXml; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripButton btnSyncXml; private System.Windows.Forms.ToolStripButton btnSelect; private System.Windows.Forms.ToolStripButton btnRefreshServers; private System.Windows.Forms.ToolStripButton btnGenDatabase; private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel; private System.Windows.Forms.ToolStripProgressBar progressIndicator; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripSplitButton btnHTML; private System.Windows.Forms.ToolStripMenuItem standardViewToolStripMenuItem; private System.Windows.Forms.ToolStripSplitButton btnCompareSelected; private System.Windows.Forms.ToolStripMenuItem createCommandlineBatchFileToolStripMenuItem; private System.Windows.Forms.ToolStripSplitButton btnGenerateSchema; private System.Windows.Forms.ToolStripMenuItem createCommandToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem compareDataFromToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectedTablesMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8; private System.Windows.Forms.ToolStripButton btnCreateDTSPackage; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9; private System.Windows.Forms.ToolStripMenuItem iconsAndTextToolStripMenuItem; private System.Windows.Forms.ToolStripPanel BottomToolStripPanel; private System.Windows.Forms.ToolStripPanel TopToolStripPanel; private System.Windows.Forms.ToolStripPanel RightToolStripPanel; private System.Windows.Forms.ToolStripPanel LeftToolStripPanel; private System.Windows.Forms.ToolStripContentPanel ContentPanel; } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using Ctrip.ObjectRenderer; using Ctrip.Core; using Ctrip.Util; using Ctrip.Plugin; namespace Ctrip.Repository { /// <summary> /// Base implementation of <see cref="ILoggerRepository"/> /// </summary> /// <remarks> /// <para> /// Default abstract implementation of the <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// Skeleton implementation of the <see cref="ILoggerRepository"/> interface. /// All <see cref="ILoggerRepository"/> types can extend this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class LoggerRepositorySkeleton : ILoggerRepository { #region Member Variables private string m_name; private RendererMap m_rendererMap; private PluginMap m_pluginMap; private LevelMap m_levelMap; private Level m_threshold; private bool m_configured; private ICollection m_configurationMessages; private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; private PropertiesDictionary m_properties; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Initializes the repository with default (empty) properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) { } /// <summary> /// Construct the repository using specific properties /// </summary> /// <param name="properties">the properties to set for this repository</param> /// <remarks> /// <para> /// Initializes the repository with specified properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton(PropertiesDictionary properties) { m_properties = properties; m_rendererMap = new RendererMap(); m_pluginMap = new PluginMap(this); m_levelMap = new LevelMap(); m_configurationMessages = EmptyCollection.Instance; m_configured = false; AddBuiltinLevels(); // Don't disable any levels by default. m_threshold = Level.All; } #endregion #region Implementation of ILoggerRepository /// <summary> /// The name of the repository /// </summary> /// <value> /// The string name of the repository /// </value> /// <remarks> /// <para> /// The name of this repository. The name is /// used to store and lookup the repositories /// stored by the <see cref="IRepositorySelector"/>. /// </para> /// </remarks> virtual public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// The threshold for all events in this repository /// </summary> /// <value> /// The threshold for all events in this repository /// </value> /// <remarks> /// <para> /// The threshold for all events in this repository /// </para> /// </remarks> virtual public Level Threshold { get { return m_threshold; } set { if (value != null) { m_threshold = value; } else { // Must not set threshold to null LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); m_threshold = Level.All; } } } /// <summary> /// RendererMap accesses the object renderer map for this repository. /// </summary> /// <value> /// RendererMap accesses the object renderer map for this repository. /// </value> /// <remarks> /// <para> /// RendererMap accesses the object renderer map for this repository. /// </para> /// <para> /// The RendererMap holds a mapping between types and /// <see cref="IObjectRenderer"/> objects. /// </para> /// </remarks> virtual public RendererMap RendererMap { get { return m_rendererMap; } } /// <summary> /// The plugin map for this repository. /// </summary> /// <value> /// The plugin map for this repository. /// </value> /// <remarks> /// <para> /// The plugin map holds the <see cref="IPlugin"/> instances /// that have been attached to this repository. /// </para> /// </remarks> virtual public PluginMap PluginMap { get { return m_pluginMap; } } /// <summary> /// Get the level map for the Repository. /// </summary> /// <remarks> /// <para> /// Get the level map for the Repository. /// </para> /// <para> /// The level map defines the mappings between /// level names and <see cref="Level"/> objects in /// this repository. /// </para> /// </remarks> virtual public LevelMap LevelMap { get { return m_levelMap; } } /// <summary> /// Test if logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the repository. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> abstract public ILogger Exists(string name); /// <summary> /// Returns all the currently defined loggers in the repository /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the repository as an Array. /// </para> /// </remarks> abstract public ILogger[] GetCurrentLoggers(); /// <summary> /// Return a new logger instance /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// Return a new logger instance. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> abstract public ILogger GetLogger(string name); /// <summary> /// Shutdown the repository /// </summary> /// <remarks> /// <para> /// Shutdown the repository. Can be overridden in a subclass. /// This base class implementation notifies the <see cref="ShutdownEvent"/> /// listeners and all attached plugins of the shutdown event. /// </para> /// </remarks> virtual public void Shutdown() { // Shutdown attached plugins foreach(IPlugin plugin in PluginMap.AllPlugins) { plugin.Shutdown(); } // Notify listeners OnShutdown(null); } /// <summary> /// Reset the repositories configuration to a default state /// </summary> /// <remarks> /// <para> /// Reset all values contained in this instance to their /// default state. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> virtual public void ResetConfiguration() { // Clear internal data structures m_rendererMap.Clear(); m_levelMap.Clear(); m_configurationMessages = EmptyCollection.Instance; // Add the predefined levels to the map AddBuiltinLevels(); Configured = false; // Notify listeners OnConfigurationReset(null); } /// <summary> /// Log the logEvent through this repository. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="M:Ctrip.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> abstract public void Log(LoggingEvent logEvent); /// <summary> /// Flag indicates if this repository has been configured. /// </summary> /// <value> /// Flag indicates if this repository has been configured. /// </value> /// <remarks> /// <para> /// Flag indicates if this repository has been configured. /// </para> /// </remarks> virtual public bool Configured { get { return m_configured; } set { m_configured = value; } } /// <summary> /// Contains a list of internal messages captures during the /// last configuration. /// </summary> virtual public ICollection ConfigurationMessages { get { return m_configurationMessages; } set { m_configurationMessages = value; } } /// <summary> /// Event to notify that the repository has been shutdown. /// </summary> /// <value> /// Event to notify that the repository has been shutdown. /// </value> /// <remarks> /// <para> /// Event raised when the repository has been shutdown. /// </para> /// </remarks> public event LoggerRepositoryShutdownEventHandler ShutdownEvent { add { m_shutdownEvent += value; } remove { m_shutdownEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration reset. /// </summary> /// <value> /// Event to notify that the repository has had its configuration reset. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been /// reset to default. /// </para> /// </remarks> public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset { add { m_configurationResetEvent += value; } remove { m_configurationResetEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration changed. /// </summary> /// <value> /// Event to notify that the repository has had its configuration changed. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been changed. /// </para> /// </remarks> public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged { add { m_configurationChangedEvent += value; } remove { m_configurationChangedEvent -= value; } } /// <summary> /// Repository specific properties /// </summary> /// <value> /// Repository specific properties /// </value> /// <remarks> /// These properties can be specified on a repository specific basis /// </remarks> public PropertiesDictionary Properties { get { return m_properties; } } /// <summary> /// Returns all the Appenders that are configured as an Array. /// </summary> /// <returns>All the Appenders</returns> /// <remarks> /// <para> /// Returns all the Appenders that are configured as an Array. /// </para> /// </remarks> abstract public Ctrip.Appender.IAppender[] GetAppenders(); #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the LoggerRepositorySkeleton class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LoggerRepositorySkeleton); #endregion Private Static Fields private void AddBuiltinLevels() { // Add the predefined levels to the map m_levelMap.Add(Level.Off); // Unrecoverable errors m_levelMap.Add(Level.Emergency); m_levelMap.Add(Level.Fatal); m_levelMap.Add(Level.Alert); // Recoverable errors m_levelMap.Add(Level.Critical); m_levelMap.Add(Level.Severe); m_levelMap.Add(Level.Error); m_levelMap.Add(Level.Warn); // Information m_levelMap.Add(Level.Notice); m_levelMap.Add(Level.Info); // Debug m_levelMap.Add(Level.Debug); m_levelMap.Add(Level.Fine); m_levelMap.Add(Level.Trace); m_levelMap.Add(Level.Finer); m_levelMap.Add(Level.Verbose); m_levelMap.Add(Level.Finest); m_levelMap.Add(Level.All); } /// <summary> /// Adds an object renderer for a specific class. /// </summary> /// <param name="typeToRender">The type that will be rendered by the renderer supplied.</param> /// <param name="rendererInstance">The object renderer used to render the object.</param> /// <remarks> /// <para> /// Adds an object renderer for a specific class. /// </para> /// </remarks> virtual public void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) { if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (rendererInstance == null) { throw new ArgumentNullException("rendererInstance"); } m_rendererMap.Put(typeToRender, rendererInstance); } /// <summary> /// Notify the registered listeners that the repository is shutting down /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository is shutting down. /// </para> /// </remarks> protected virtual void OnShutdown(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryShutdownEventHandler handler = m_shutdownEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration reset /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has been reset. /// </para> /// </remarks> protected virtual void OnConfigurationReset(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationResetEventHandler handler = m_configurationResetEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration changed /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has changed. /// </para> /// </remarks> protected virtual void OnConfigurationChanged(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationChangedEventHandler handler = m_configurationChangedEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Raise a configuration changed event on this repository /// </summary> /// <param name="e">EventArgs.Empty</param> /// <remarks> /// <para> /// Applications that programmatically change the configuration of the repository should /// raise this event notification to notify listeners. /// </para> /// </remarks> public void RaiseConfigurationChanged(EventArgs e) { OnConfigurationChanged(e); } } }
// // Application.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Library; using Banshee.Playlist; using Banshee.SmartPlaylist; using Banshee.Sources; using Banshee.Base; namespace Banshee.ServiceStack { public delegate bool ShutdownRequestHandler (); public delegate bool TimeoutHandler (); public delegate bool IdleHandler (); public delegate bool IdleTimeoutRemoveHandler (uint id); public delegate uint TimeoutImplementationHandler (uint milliseconds, TimeoutHandler handler); public delegate uint IdleImplementationHandler (IdleHandler handler); public delegate bool IdleTimeoutRemoveImplementationHandler (uint id); public static class Application { public static event ShutdownRequestHandler ShutdownRequested; public static event Action<Client> ClientAdded; private static event Action<Client> client_started; public static event Action<Client> ClientStarted { add { lock (running_clients) { foreach (Client client in running_clients) { if (client.IsStarted) { OnClientStarted (client); } } } client_started += value; } remove { client_started -= value; } } private static Stack<Client> running_clients = new Stack<Client> (); private static bool shutting_down; public static void Initialize () { ServiceManager.DefaultInitialize (); } #if WIN32 [DllImport("msvcrt.dll") /* willfully unmapped */] public static extern int _putenv (string varName); #endif public static void Run () { #if WIN32 // There are two sets of environement variables we need to impact with our LANG. // refer to : http://article.gmane.org/gmane.comp.gnu.mingw.user/8272 var lang_code = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; string env = String.Concat ("LANG=", lang_code); Environment.SetEnvironmentVariable ("LANG", lang_code); _putenv (env); #endif Catalog.Init (Application.InternalName, System.IO.Path.Combine ( Hyena.Paths.InstalledApplicationDataRoot, "locale")); DBusConnection.Init (); ServiceManager.Run (); ServiceManager.SourceManager.AddSource (new MusicLibrarySource (), true); ServiceManager.SourceManager.AddSource (new VideoLibrarySource (), false); ServiceManager.SourceManager.LoadExtensionSources (); } public static bool ShuttingDown { get { return shutting_down; } } public static void Shutdown () { shutting_down = true; if (Banshee.Kernel.Scheduler.IsScheduled (typeof (Banshee.Kernel.IInstanceCriticalJob)) || ServiceManager.JobScheduler.HasAnyDataLossJobs || Banshee.Kernel.Scheduler.CurrentJob is Banshee.Kernel.IInstanceCriticalJob) { if (shutdown_prompt_handler != null && !shutdown_prompt_handler ()) { shutting_down = false; return; } } if (OnShutdownRequested ()) { Dispose (); } shutting_down = false; } public static void PushClient (Client client) { lock (running_clients) { running_clients.Push (client); client.Started += OnClientStarted; } Action<Client> handler = ClientAdded; if (handler != null) { handler (client); } } public static Client PopClient () { lock (running_clients) { return running_clients.Pop (); } } public static Client ActiveClient { get { lock (running_clients) { return running_clients.Peek (); } } } private static void OnClientStarted (Client client) { client.Started -= OnClientStarted; Action<Client> handler = client_started; if (handler != null) { handler (client); } } static bool paths_initialized; public static void InitializePaths () { if (!paths_initialized) { // We changed banshee-1 to banshee everywhere except the // ~/.config/banshee-1/ and ~/.cache/banshee-1 directories, and // for gconf Paths.UserApplicationName = "banshee-1"; Paths.ApplicationName = InternalName; paths_initialized = true; } } [DllImport ("libglib-2.0-0.dll")] static extern IntPtr g_get_language_names (); public static void DisplayHelp (string page) { DisplayHelp ("banshee", page); } private static void DisplayHelp (string project, string page) { bool shown = false; foreach (var lang in GLib.Marshaller.NullTermPtrToStringArray (g_get_language_names (), false)) { string path = String.Format ("{0}/gnome/help/{1}/{2}", Paths.InstalledApplicationDataRoot, project, lang); if (System.IO.Directory.Exists (path)) { shown = Banshee.Web.Browser.Open (String.Format ("ghelp:{0}", path), false); break; } } if (!shown) { Banshee.Web.Browser.Open (String.Format ("http://library.gnome.org/users/{0}/", project)); } } private static bool OnShutdownRequested () { ShutdownRequestHandler handler = ShutdownRequested; if (handler != null) { foreach (ShutdownRequestHandler del in handler.GetInvocationList ()) { if (!del ()) { return false; } } } return true; } public static void Invoke (InvokeHandler handler) { RunIdle (delegate { handler (); return false; }); } public static uint RunIdle (IdleHandler handler) { if (idle_handler == null) { throw new NotImplementedException ("The application client must provide an IdleImplementationHandler"); } return idle_handler (handler); } public static uint RunTimeout (uint milliseconds, TimeoutHandler handler) { if (timeout_handler == null) { throw new NotImplementedException ("The application client must provide a TimeoutImplementationHandler"); } return timeout_handler (milliseconds, handler); } public static bool IdleTimeoutRemove (uint id) { if (idle_timeout_remove_handler == null) { throw new NotImplementedException ("The application client must provide a IdleTimeoutRemoveImplementationHandler"); } return idle_timeout_remove_handler (id); } private static void Dispose () { ServiceManager.JobScheduler.CancelAll (true); ServiceManager.Shutdown (); lock (running_clients) { while (running_clients.Count > 0) { running_clients.Pop ().Dispose (); } } } private static ShutdownRequestHandler shutdown_prompt_handler = null; public static ShutdownRequestHandler ShutdownPromptHandler { get { return shutdown_prompt_handler; } set { shutdown_prompt_handler = value; } } private static TimeoutImplementationHandler timeout_handler = null; public static TimeoutImplementationHandler TimeoutHandler { get { return timeout_handler; } set { timeout_handler = value; } } private static IdleImplementationHandler idle_handler = null; public static IdleImplementationHandler IdleHandler { get { return idle_handler; } set { idle_handler = value; } } private static IdleTimeoutRemoveImplementationHandler idle_timeout_remove_handler = null; public static IdleTimeoutRemoveImplementationHandler IdleTimeoutRemoveHandler { get { return idle_timeout_remove_handler; } set { idle_timeout_remove_handler = value; } } public static string InternalName { get { return "banshee"; } } public static string IconName { get { return "media-player-banshee"; } } private static string api_version; public static string ApiVersion { get { if (api_version != null) { return api_version; } try { AssemblyName name = Assembly.GetEntryAssembly ().GetName (); api_version = String.Format ("{0}.{1}.{2}", name.Version.Major, name.Version.Minor, name.Version.Build); } catch { api_version = "unknown"; } return api_version; } } private static string version; public static string Version { get { return version ?? (version = GetVersion ("ReleaseVersion")); } } private static string display_version; public static string DisplayVersion { get { return display_version ?? (display_version = GetVersion ("DisplayVersion")); } } private static string build_time; public static string BuildTime { get { return build_time ?? (build_time = GetBuildInfo ("BuildTime")); } } private static string build_host_os; public static string BuildHostOperatingSystem { get { return build_host_os ?? (build_host_os = GetBuildInfo ("HostOperatingSystem")); } } private static string build_host_cpu; public static string BuildHostCpu { get { return build_host_cpu ?? (build_host_cpu = GetBuildInfo ("HostCpu")); } } private static string build_vendor; public static string BuildVendor { get { return build_vendor ?? (build_vendor = GetBuildInfo ("Vendor")); } } private static string build_display_info; public static string BuildDisplayInfo { get { if (build_display_info != null) { return build_display_info; } build_display_info = String.Format ("{0} ({1}, {2}) @ {3}", BuildVendor, BuildHostOperatingSystem, BuildHostCpu, BuildTime); return build_display_info; } } private static string GetVersion (string versionName) { return GetCustomAssemblyMetadata ("ApplicationVersionAttribute", versionName) ?? Catalog.GetString ("Unknown"); } private static string GetBuildInfo (string buildField) { return GetCustomAssemblyMetadata ("ApplicationBuildInformationAttribute", buildField); } private static string GetCustomAssemblyMetadata (string attrName, string field) { Assembly assembly = Assembly.GetEntryAssembly (); if (assembly == null) { return null; } foreach (Attribute attribute in assembly.GetCustomAttributes (false)) { Type type = attribute.GetType (); PropertyInfo property = type.GetProperty (field); if (type.Name == attrName && property != null && property.PropertyType == typeof (string)) { return (string)property.GetValue (attribute, null); } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if USE_REFEMIT || uapaot public class XmlObjectSerializerReadContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { internal Attributes attributes; private HybridObjectCache _deserializedObjects; private XmlSerializableReader _xmlSerializableReader; private XmlDocument _xmlDocument; private Attributes _attributesInXmlData; private object _getOnlyCollectionValue; private bool _isGetOnlyCollection; private HybridObjectCache DeserializedObjects { get { if (_deserializedObjects == null) _deserializedObjects = new HybridObjectCache(); return _deserializedObjects; } } private XmlDocument Document => _xmlDocument ?? (_xmlDocument = new XmlDocument()); internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } #if USE_REFEMIT public object GetCollectionMember() #else internal object GetCollectionMember() #endif { return _getOnlyCollectionValue; } #if USE_REFEMIT public void StoreCollectionMemberInfo(object collectionMember) #else internal void StoreCollectionMemberInfo(object collectionMember) #endif { _getOnlyCollectionValue = collectionMember; _isGetOnlyCollection = true; } internal void ResetCollectionMemberInfo() { _getOnlyCollectionValue = null; _isGetOnlyCollection = false; } #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } #if uapaot // Referenced from generated code in .NET Native's SerializationAssemblyGenerator internal static void ThrowNoDefaultConstructorForCollectionException(Type type) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoDefaultConstructorForCollection, DataContract.GetClrTypeFullName(type)))); } #endif #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else internal static void ThrowArrayExceededSizeException(int arraySize, Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); } #if USE_REFEMIT public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #else internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #endif { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, Type.GetTypeFromHandle(declaredTypeHandle), ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (_isGetOnlyCollection) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(declaredType)), SR.Format(SR.XmlStartElementExpected, Globals.RefLocalName)))); } else { retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } } else if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, Type declaredType, ref DataContract dataContract) { object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); if (dataContract == null) { if (DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (dataContract.IsISerializable && attributes.FactoryTypeName != null) { DataContract factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); if (factoryDataContract != null) { if (factoryDataContract.IsISerializable) { dataContract = factoryDataContract; knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryTypeNotISerializable, DataContract.GetClrTypeFullName(factoryDataContract.UnderlyingType), DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } } } if (knownTypesAddedInCurrentScope) { object obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } else { return ReadDataContractValue(dataContract, reader); } } private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } #if USE_REFEMIT public static bool MoveToNextElement(XmlReaderDelegator xmlReader) #else internal static bool MoveToNextElement(XmlReaderDelegator xmlReader) #endif { return (xmlReader.MoveToContent() != XmlNodeType.EndElement); } #if USE_REFEMIT public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) return i; } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #else internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #endif { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) requiredIndex--; for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) stringBuilder.Append(" | "); stringBuilder.Append(memberNames[i].Value); } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } #if uapaot public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int missingMembersCount = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(memberNames[i]); missingMembersCount++; } } if (missingMembersCount == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } } public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); } private static bool IsBitSet(byte[] bytes, int bitIndex) { throw new NotImplementedException(); //return BitFlagsGenerator.IsBitSet(bytes, bitIndex); } #endif protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (IgnoreExtensionDataObject || extensionData == null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { if (extensionData.Members == null) extensionData.Members = new List<ExtensionDataMember>(); extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } #if USE_REFEMIT public void SkipUnknownElement(XmlReaderDelegator xmlReader) #else internal void SkipUnknownElement(XmlReaderDelegator xmlReader) #endif { ReadAttributes(xmlReader); xmlReader.Skip(); } #if USE_REFEMIT public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #else internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #endif { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } else if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return Globals.NullObjectId; } return Globals.NewObjectId; } #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) #endif { if (attributes == null) attributes = new Attributes(); attributes.Read(xmlReader); } #if USE_REFEMIT public void ResetAttributes() #else internal void ResetAttributes() #endif { if (attributes != null) attributes.Reset(); } #if USE_REFEMIT public string GetObjectId() #else internal string GetObjectId() #endif { return attributes.Id; } #if USE_REFEMIT public virtual int GetArraySize() #else internal virtual int GetArraySize() #endif { return -1; } #if USE_REFEMIT public void AddNewObject(object obj) #else internal void AddNewObject(object obj) #endif { AddNewObjectWithId(attributes.Id, obj); } #if USE_REFEMIT public void AddNewObjectWithId(string id, object obj) #else internal void AddNewObjectWithId(string id, object obj) #endif { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; if (id != Globals.NewObjectId) { // In certain cases (IObjectReference, SerializationSurrogate or DataContractSurrogate), // an object can be replaced with a different object once it is deserialized. If the // object happens to be referenced from within itself, that reference needs to be updated // with the new instance. BinaryFormatter supports this by fixing up such references later. // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } } #if USE_REFEMIT public object GetExistingObject(string id, Type type, string name, string ns) #else internal object GetExistingObject(string id, Type type, string name, string ns) #endif { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } private object GetExistingObjectOrExtensionData(string id) { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); } return retObj; } public object GetRealObject(IObjectReference obj, string id) { object realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext()); // If GetRealObject returns null, it indicates that the object could not resolve itself because // it is missing information. This may occur in a case where multiple IObjectReference instances // depend on each other. BinaryFormatter supports this by fixing up the references later. These // XmlObjectSerializer implementations do not support fix-ups since the format does not contain // forward references. However, we throw for this case since it allows us to add fix-up support // in the future if we need to. if (realObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException("error")); ReplaceDeserializedObject(id, obj, realObj); return realObj; } #if USE_REFEMIT public static void Read(XmlReaderDelegator xmlReader) #else internal static void Read(XmlReaderDelegator xmlReader) #endif { if (!xmlReader.Read()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; if (colon >= 0) prefix = qname.Substring(0, colon); name = qname.Substring(colon + 1); ns = xmlReader.LookupNamespace(prefix); } #if USE_REFEMIT public static T[] EnsureArraySize<T>(T[] array, int index) #else internal static T[] EnsureArraySize<T>(T[] array, int index) #endif { if (array.Length <= index) { if (index == int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException( SR.Format(SR.MaxArrayLengthExceeded, int.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } int newSize = (index < int.MaxValue / 2) ? index * 2 : int.MaxValue; T[] newArray = new T[newSize]; Array.Copy(array, 0, newArray, 0, array.Length); array = newArray; } return array; } #if USE_REFEMIT public static T[] TrimArraySize<T>(T[] array, int size) #else internal static T[] TrimArraySize<T>(T[] array, int size) #endif { if (size != array.Length) { T[] newArray = new T[size]; Array.Copy(array, 0, newArray, 0, size); array = newArray; } return array; } #if USE_REFEMIT public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #else internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #endif { if (xmlReader.NodeType == XmlNodeType.EndElement) return; while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, arraySize, itemName.Value, itemNamespace.Value))); SkipUnknownElement(xmlReader); } if (xmlReader.NodeType != XmlNodeType.EndElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (_xmlSerializableReader == null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlElement) { if (!xmlReader.IsStartElement()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); XmlDocument xmlDoc = new XmlDocument(); obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { obj = XmlSerializableServices.ReadNodes(xmlSerializableReader); } else { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Type type) { var serInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } string name = XmlConvert.DecodeName(xmlReader.LocalName); IncrementItemCount(1); ReadAttributes(xmlReader); object value; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); value = GetExistingObject(attributes.Ref, null, name, string.Empty); } else if (attributes.XsiNil) { xmlReader.Skip(); value = null; } else { value = InternalDeserialize(xmlReader, Globals.TypeOfObject, name, string.Empty); } serInfo.AddValue(name, value); } return serInfo; } protected virtual DataContract ResolveDataContractFromTypeName() { return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null); } private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) { var member = new ExtensionDataMember { Name = xmlReader.LocalName, Namespace = xmlReader.NamespaceURI, MemberIndex = memberIndex }; member.Value = xmlReader.UnderlyingExtensionDataReader != null ? xmlReader.UnderlyingExtensionDataReader.GetCurrentNode() : ReadExtensionDataValue(xmlReader); return member; } public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); IncrementItemCount(1); IDataNode dataNode = null; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); object o = GetExistingObjectOrExtensionData(attributes.Ref); dataNode = (o is IDataNode) ? (IDataNode)o : new DataNode<object>(o); dataNode.Id = attributes.Ref; } else if (attributes.XsiNil) { xmlReader.Skip(); dataNode = null; } else { string dataContractName = null; string dataContractNamespace = null; if (attributes.XsiTypeName != null) { dataContractName = attributes.XsiTypeName; dataContractNamespace = attributes.XsiTypeNamespace; } if (IsReadingCollectionExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } else if (attributes.FactoryTypeName != null) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (IsReadingClassExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else { DataContract dataContract = ResolveDataContractFromTypeName(); if (dataContract == null) dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); else if (dataContract is XmlDataContract) dataNode = ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); else { if (dataContract.IsISerializable) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is PrimitiveDataContract) { if (attributes.Id == Globals.NewObjectId) { Read(xmlReader); xmlReader.MoveToContent(); dataNode = ReadUnknownPrimitiveData(xmlReader, dataContract.UnderlyingType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); } else { dataNode = new DataNode<object>(xmlReader.ReadElementContentAsAnyType(dataContract.UnderlyingType)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } } else if (dataContract is EnumDataContract) { dataNode = new DataNode<object>(((EnumDataContract)dataContract).ReadEnumValue(xmlReader)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } else if (dataContract is ClassDataContract) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is CollectionDataContract) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } } } } return dataNode; } protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { } private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { StartReadExtensionDataValue(xmlReader); if (attributes.UnrecognizedAttributesFound) return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); IDictionary<string, string> namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); Read(xmlReader); xmlReader.MoveToContent(); switch (xmlReader.NodeType) { case XmlNodeType.Text: return ReadPrimitiveExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); case XmlNodeType.Element: if (xmlReader.NamespaceURI.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal)) return ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); else return ReadAndResolveUnknownXmlData(xmlReader, namespacesInScope, dataContractName, dataContractNamespace); case XmlNodeType.EndElement: { // NOTE: cannot distinguish between empty class or IXmlSerializable and typeof(object) IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, Globals.TypeOfObject, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); objNode.IsFinalValue = false; return objNode; } default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } } protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { Type valueType = xmlReader.ValueType; if (valueType == Globals.TypeOfString) { // NOTE: cannot distinguish other primitives from string (default XmlReader ValueType) IDataNode stringNode = new DataNode<object>(xmlReader.ReadContentAsString()); InitializeExtensionDataNode(stringNode, dataContractName, dataContractNamespace); stringNode.IsFinalValue = false; xmlReader.ReadEndElement(); return stringNode; } IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, valueType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); return objNode; } protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace) { dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; dataNode.ClrAssemblyName = attributes.ClrAssembly; dataNode.ClrTypeName = attributes.ClrType; AddNewObject(dataNode); dataNode.Id = attributes.Id; } private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace) { IDataNode dataNode = xmlReader.ReadExtensionData(type); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); return dataNode; } private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new ClassDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int memberIndex = 0; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.Members == null) dataNode.Members = new List<ExtensionDataMember>(); dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++)); } xmlReader.ReadEndElement(); return dataNode; } private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new CollectionDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int arraySize = attributes.ArraySZSize; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.ItemName == null) { dataNode.ItemName = xmlReader.LocalName; dataNode.ItemNamespace = xmlReader.NamespaceURI; } if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace)) { if (dataNode.Items == null) dataNode.Items = new List<IDataNode>(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else SkipUnknownElement(xmlReader); } xmlReader.ReadEndElement(); if (arraySize != -1) { dataNode.Size = arraySize; if (dataNode.Items == null) { if (dataNode.Size > 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, 0))); } else if (dataNode.Size != dataNode.Items.Count) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, dataNode.Items.Count))); } else { if (dataNode.Items != null) { dataNode.Size = dataNode.Items.Count; } else { dataNode.Size = 0; } } return dataNode; } private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new ISerializableDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.FactoryTypeName = attributes.FactoryTypeName; dataNode.FactoryTypeNamespace = attributes.FactoryTypeNamespace; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } var member = new ISerializableDataMember(); member.Name = xmlReader.LocalName; member.Value = ReadExtensionDataValue(xmlReader); if (dataNode.Members == null) dataNode.Members = new List<ISerializableDataMember>(); dataNode.Members.Add(member); } xmlReader.ReadEndElement(); return dataNode; } private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; if (xmlReader.NodeType == XmlNodeType.EndElement) return dataNode; IList<XmlAttribute> xmlAttributes = null; IList<XmlNode> xmlChildNodes = null; XmlNodeType nodeType = xmlReader.MoveToContent(); if (nodeType != XmlNodeType.Text) { while (xmlReader.MoveToNextAttribute()) { string ns = xmlReader.NamespaceURI; if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace) { if (xmlAttributes == null) xmlAttributes = new List<XmlAttribute>(); xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)); } } Read(xmlReader); } while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); if (xmlChildNodes == null) xmlChildNodes = new List<XmlNode>(); xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)); } xmlReader.ReadEndElement(); dataNode.XmlAttributes = xmlAttributes; dataNode.XmlChildNodes = xmlChildNodes; return dataNode; } // Pattern-recognition logic: the method reads XML elements into DOM. To recognize as an array, it requires that // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a // class/class hierarchy. Otherwise it is deserialized as XML. private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary<string, string> namespaces, string dataContractName, string dataContractNamespace) { bool couldBeISerializableData = true; bool couldBeCollectionData = true; bool couldBeClassData = true; string elementNs = null, elementName = null; var xmlChildNodes = new List<XmlNode>(); IList<XmlAttribute> xmlAttributes = null; if (namespaces != null) { xmlAttributes = new List<XmlAttribute>(); foreach (KeyValuePair<string, string> prefixNsPair in namespaces) { xmlAttributes.Add(AddNamespaceDeclaration(prefixNsPair.Key, prefixNsPair.Value)); } } XmlNodeType nodeType; while ((nodeType = xmlReader.NodeType) != XmlNodeType.EndElement) { if (nodeType == XmlNodeType.Element) { string ns = xmlReader.NamespaceURI; string name = xmlReader.LocalName; if (couldBeISerializableData) couldBeISerializableData = (ns.Length == 0); if (couldBeCollectionData) { if (elementName == null) { elementName = name; elementNs = ns; } else couldBeCollectionData = (string.CompareOrdinal(elementName, name) == 0) && (string.CompareOrdinal(elementNs, ns) == 0); } } else if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); else if (IsContentNode(xmlReader.NodeType)) couldBeClassData = couldBeISerializableData = couldBeCollectionData = false; if (_attributesInXmlData == null) _attributesInXmlData = new Attributes(); _attributesInXmlData.Read(xmlReader); XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader); xmlChildNodes.Add(childNode); if (namespaces == null) { if (_attributesInXmlData.XsiTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace)); if (_attributesInXmlData.FactoryTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace)); } } xmlReader.ReadEndElement(); if (elementName != null && couldBeCollectionData) return ReadUnknownCollectionData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeISerializableData) return ReadUnknownISerializableData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeClassData) return ReadUnknownClassData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; dataNode.XmlChildNodes = xmlChildNodes; dataNode.XmlAttributes = xmlAttributes; return dataNode; } } private bool IsContentNode(XmlNodeType nodeType) { switch (nodeType) { case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return false; default: return true; } } internal XmlReaderDelegator CreateReaderOverChildNodes(IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes) { XmlNode wrapperElement = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null); XmlReaderDelegator nodeReader = CreateReaderDelegatorForReader(new XmlNodeReader(wrapperElement)); nodeReader.MoveToContent(); Read(nodeReader); return nodeReader; } internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes, string prefix, string localName, string ns) { localName = localName ?? "wrapper"; ns = ns ?? string.Empty; XmlNode wrapperElement = document.CreateElement(prefix, localName, ns); if (xmlAttributes != null) { for (int i = 0; i < xmlAttributes.Count; i++) { wrapperElement.Attributes.Append((XmlAttribute) xmlAttributes[i]); } } if (xmlChildNodes != null) { for (int i = 0; i < xmlChildNodes.Count; i++) { wrapperElement.AppendChild(xmlChildNodes[i]); } } return wrapperElement; } private XmlAttribute AddNamespaceDeclaration(string prefix, string ns) { XmlAttribute attribute = (prefix == null || prefix.Length == 0) ? Document.CreateAttribute(null, Globals.XmlnsPrefix, Globals.XmlnsNamespace) : Document.CreateAttribute(Globals.XmlnsPrefix, prefix, Globals.XmlnsNamespace); attribute.Value = ns; return attribute; } #if USE_REFEMIT public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #else internal static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #endif { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingState, expectedState), xmlReader); } //Silverlight only helper function to create SerializationException #if USE_REFEMIT public static Exception CreateSerializationException(string message) #else internal static Exception CreateSerializationException(string message) #endif { return XmlObjectSerializer.CreateSerializationException(message); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return (attributes.ArraySZSize != -1); } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } }
//------------------------------------------------------------------------------ // <copyright file="_DigestClient.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Net.Sockets; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Permissions; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Security; using System.Diagnostics; internal class DigestClient : ISessionAuthenticationModule { internal const string AuthType = "Digest"; internal static string Signature = AuthType.ToLower(CultureInfo.InvariantCulture); internal static int SignatureSize = Signature.Length; private static PrefixLookup challengeCache = new PrefixLookup(); private static readonly char[] singleSpaceArray = new char[]{' '}; // [....]: make sure WDigest fixes these bugs before we // enable this code ("Windows OS" Product Studio database): // // 921024 1 Wdigest should support MD5, at least for explicit (non-default) credentials. // 762116 2 WDigest should ignore directives that do not have a value // 762115 3 WDigest should allow an application to retrieve the parsed domain directive // private static bool _WDigestAvailable; static DigestClient() { _WDigestAvailable = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, NegotiationInfoClass.WDigest)!=null; } public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) { GlobalLog.Print("DigestClient::Authenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()"); return DoAuthenticate(challenge, webRequest, credentials, false); } private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { GlobalLog.Print("DigestClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString()); GlobalLog.Assert(credentials != null, "DigestClient::DoAuthenticate()|credentials == null"); if (credentials==null) { return null; } HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "DigestClient::DoAuthenticate()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "DigestClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null"); // If it's default credentials, we support them on XP and up through WDigest. NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, DigestClient.Signature); GlobalLog.Print("DigestClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC)); if (NC is SystemNetworkCredential) { if (WDigestAvailable) { return XPDoAuthenticate(challenge, httpWebRequest, credentials, preAuthenticate); } else { return null; } } HttpDigestChallenge digestChallenge; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return null; } digestChallenge = HttpDigest.Interpret(challenge, index, httpWebRequest); } else { GlobalLog.Print("DigestClient::DoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri); digestChallenge = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge; } if (digestChallenge==null) { return null; } bool supported = CheckQOP(digestChallenge); if (!supported) { if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_digest_qop_not_supported, digestChallenge.QualityOfProtection)); return null; } if (preAuthenticate) { GlobalLog.Print("DigestClient::DoAuthenticate() retrieved digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri); digestChallenge = digestChallenge.CopyAndIncrementNonce(); digestChallenge.SetFromRequest(httpWebRequest); } if (NC==null) { return null; } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) return null; SpnToken spnToken = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } Authorization digestResponse = HttpDigest.Authenticate(digestChallenge, NC, spnToken.Spn, binding); if (!preAuthenticate && webRequest.PreAuthenticate && digestResponse != null) { // add this to the cache of challenges so we can preauthenticate string[] prefixes = digestChallenge.Domain==null ? new string[]{httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped)} : digestChallenge.Domain.Split(singleSpaceArray); // If Domain property is not set we associate Digest only with the server Uri namespace (used to do with whole server) digestResponse.ProtectionRealm = digestChallenge.Domain==null ? null: prefixes; for (int i=0; i<prefixes.Length; i++) { GlobalLog.Print("DigestClient::DoAuthenticate() adding digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " for prefix:" + prefixes[i]); challengeCache.Add(prefixes[i], digestChallenge); } } return digestResponse; } public Authorization PreAuthenticate(WebRequest webRequest, ICredentials credentials) { GlobalLog.Print("DigestClient::PreAuthenticate() webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()"); return DoAuthenticate(null, webRequest, credentials, true); } public bool CanPreAuthenticate { get { return true; } } public string AuthenticationType { get { return AuthType; } } internal static bool CheckQOP(HttpDigestChallenge challenge) { // our internal implementatoin only support "auth" QualityOfProtection. // if it's not what the server wants we'll have to throw: // the case in which the server sends no qop directive we default to "auth" if (challenge.QopPresent) { int index = 0; while (index>=0) { // find the next occurence of "auth" index = challenge.QualityOfProtection.IndexOf(HttpDigest.SupportedQuality, index); if (index<0) { return false; } // if it's a whole word we're done if ((index==0 || HttpDigest.ValidSeparator.IndexOf(challenge.QualityOfProtection[index - 1])>=0) && (index+HttpDigest.SupportedQuality.Length==challenge.QualityOfProtection.Length || HttpDigest.ValidSeparator.IndexOf(challenge.QualityOfProtection[index + HttpDigest.SupportedQuality.Length])>=0) ) { break; } index += HttpDigest.SupportedQuality.Length; } } return true; } public bool Update(string challenge, WebRequest webRequest) { GlobalLog.Print("DigestClient::Update(): [" + challenge + "]"); HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest!=null, "DigestClient::Update()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "DigestClient::Update()|httpWebRequest.ChallengedUri == null"); // make sure WDigest fixes these bugs before we enable this code ("Windows OS"): // 921024 1 WDigest should support MD5, at least for explicit (non-default) credentials. // 762116 2 WDigest should ignore directives that do not have a value // 762115 3 WDigest should allow an application to retrieve the parsed domain directive if (httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this) != null) { return XPUpdate(challenge, httpWebRequest); } // here's how we know if the handshake is complete when we get the response back, // (keeping in mind that we need to support stale credentials): // !40X - complete & success // 40X & stale=false - complete & failure // 40X & stale=true - !complete if (httpWebRequest.ResponseStatusCode!=httpWebRequest.CurrentAuthenticationState.StatusCodeMatch) { GlobalLog.Print("DigestClient::Update(): no status code match. returning true"); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, binding); return true; } int index = challenge==null ? -1 : AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { GlobalLog.Print("DigestClient::Update(): no challenge. returning true"); return true; } int blobBegin = index + SignatureSize; string incoming = null; // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { incoming = challenge.Substring(blobBegin); } HttpDigestChallenge digestChallenge = HttpDigest.Interpret(challenge, index, httpWebRequest); if (digestChallenge==null) { GlobalLog.Print("DigestClient::Update(): not a valid digest challenge. returning true"); return true; } GlobalLog.Print("DigestClient::Update(): returning digestChallenge.Stale:" + digestChallenge.Stale.ToString()); return !digestChallenge.Stale; } public bool CanUseDefaultCredentials { get { return WDigestAvailable; } } internal static bool WDigestAvailable { get { return _WDigestAvailable; } } public void ClearSession(WebRequest webRequest) { HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "NtlmClient::ClearSession()|httpWebRequest == null"); // when we're using WDigest.dll we need to keep the NTAuthentication instance around, since it's in the // challengeCache so remove the reference in the AuthenticationState to avoid closing it in ClearSession #if WDIGEST_PREAUTH httpWebRequest.CurrentAuthenticationState.SetSecurityContext(null, this); #else httpWebRequest.CurrentAuthenticationState.ClearSession(); #endif } // On Windows XP and up, WDigest.dll supports the Digest authentication scheme (in addition to // support for HTTP client sides, it also supports HTTP server side and SASL) through SSPI. private Authorization XPDoAuthenticate(string challenge, HttpWebRequest httpWebRequest, ICredentials credentials, bool preAuthenticate) { GlobalLog.Print("DigestClient::XPDoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] httpWebRequest#" + ValidationHelper.HashString(httpWebRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString()); NTAuthentication authSession = null; string incoming = null; int index; if (!preAuthenticate) { index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return null; } authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("DigestClient::XPDoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); incoming = RefineDigestChallenge(challenge, index); } else { #if WDIGEST_PREAUTH GlobalLog.Print("DigestClient::XPDoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri); authSession = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as NTAuthentication; if (authSession==null) { return null; } #else GlobalLog.Print("DigestClient::XPDoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri); HttpDigestChallenge digestChallenge = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge; if (digestChallenge==null) { return null; } GlobalLog.Print("DigestClient::XPDoAuthenticate() retrieved digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri); digestChallenge = digestChallenge.CopyAndIncrementNonce(); digestChallenge.SetFromRequest(httpWebRequest); incoming = digestChallenge.ToBlob(); #endif } UriComponents uriParts = 0; Uri remoteUri = httpWebRequest.GetRemoteResourceUri(); if (httpWebRequest.CurrentMethod.ConnectRequest) { uriParts = UriComponents.HostAndPort; // Use the orriginal request Uri, not the proxy Uri remoteUri = httpWebRequest.RequestUri; } else { uriParts = UriComponents.PathAndQuery; } // here we use Address instead of ChallengedUri. This is because the // Digest hash is generated using the uri as it is present on the wire string rawUri = remoteUri.GetParts(uriParts, UriFormat.UriEscaped); GlobalLog.Print("DigestClient::XPDoAuthenticate() rawUri:" + ValidationHelper.ToString(rawUri)); if (authSession==null) { NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); GlobalLog.Print("DigestClient::XPDoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC)); if (NC == null || (!(NC is SystemNetworkCredential) && NC.InternalGetUserName().Length == 0)) { return null; } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) return null; SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); GlobalLog.Print("NtlmClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn)); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } authSession = new NTAuthentication( NegotiationInfoClass.WDigest, NC, spn, httpWebRequest, binding); GlobalLog.Print("DigestClient::XPDoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession)); httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this); } SecurityStatus statusCode; string clientResponse; GlobalLog.Print("DigestClient::XPDoAuthenticate() incoming:" + ValidationHelper.ToString(incoming)); #if WDIGEST_PREAUTH clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, rawUri, null, preAuthenticate, true, out statusCode); #else clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, rawUri, null, false, false, out statusCode); #endif if (clientResponse == null) return null; GlobalLog.Print("DigestClient::XPDoAuthenticate() GetOutgoingDigestBlob(" + incoming + ") returns:" + ValidationHelper.ToString(clientResponse)); Authorization digestResponse = new Authorization(AuthType + " " + clientResponse, authSession.IsCompleted, string.Empty, authSession.IsMutualAuthFlag); if (!preAuthenticate && httpWebRequest.PreAuthenticate) { // add this to the cache of challenges so we can preauthenticate // use this DCR when avaialble to do this without calling HttpDigest.Interpret(): // 762115 3 WDigest should allow an application to retrieve the parsed domain directive HttpDigestChallenge digestChallenge = HttpDigest.Interpret(incoming, -1, httpWebRequest); string[] prefixes = digestChallenge.Domain==null ? new string[]{httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped)} : digestChallenge.Domain.Split(singleSpaceArray); // If Domain property is not set we associate Digest only with the server Uri namespace (used to do with whole server) digestResponse.ProtectionRealm = digestChallenge.Domain==null ? null: prefixes; for (int i=0; i<prefixes.Length; i++) { GlobalLog.Print("DigestClient::XPDoAuthenticate() adding authSession#" + ValidationHelper.HashString(authSession) + " for prefix:" + prefixes[i]); #if WDIGEST_PREAUTH challengeCache.Add(prefixes[i], authSession); #else challengeCache.Add(prefixes[i], digestChallenge); #endif } } return digestResponse; } private bool XPUpdate(string challenge, HttpWebRequest httpWebRequest) { GlobalLog.Print("DigestClient::XPUpdate(): " + challenge); NTAuthentication authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("DigestClient::XPUpdate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); if (authSession==null) { return false; } int index = challenge==null ? -1 : AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { GlobalLog.Print("DigestClient::XPUpdate(): no challenge. returning true"); // Extract the CBT we used and cache it for future requests that want to do preauth httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding); ClearSession(httpWebRequest); return true; } // here's how we know if the handshake is complete when we get the response back, // (keeping in mind that we need to support stale credentials): // !40X - complete & success // 40X & stale=false - complete & failure // 40X & stale=true - !complete if (httpWebRequest.ResponseStatusCode!=httpWebRequest.CurrentAuthenticationState.StatusCodeMatch) { GlobalLog.Print("DigestClient::XPUpdate(): no status code match. returning true"); // Extract the CBT we used and cache it for future requests that want to do preauth httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding); ClearSession(httpWebRequest); return true; } string incoming = RefineDigestChallenge(challenge, index); GlobalLog.Print("DigestClient::XPDoAuthenticate() incoming:" + ValidationHelper.ToString(incoming)); // we should get here only on invalid or stale credentials: SecurityStatus statusCode; string clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, null, null, false, true, out statusCode); httpWebRequest.CurrentAuthenticationState.Authorization.MutuallyAuthenticated = authSession.IsMutualAuthFlag; GlobalLog.Print("DigestClient::XPUpdate() GetOutgoingDigestBlob(" + incoming + ") returns:" + ValidationHelper.ToString(clientResponse)); GlobalLog.Assert(authSession.IsCompleted, "DigestClient::XPUpdate()|IsCompleted == false"); GlobalLog.Print("DigestClient::XPUpdate() GetOutgoingBlob() returns clientResponse:[" + ValidationHelper.ToString(clientResponse) + "] IsCompleted:" + authSession.IsCompleted.ToString()); return authSession.IsCompleted; } // // Extract digest relevant part from a raw server blob // private static string RefineDigestChallenge(string challenge, int index) { string incoming = null; Debug.Assert(challenge != null); Debug.Assert(index >= 0 && index < challenge.Length); int blobBegin = index + SignatureSize; // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { incoming = challenge.Substring(blobBegin); } else { Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_auth_invalid_challenge, DigestClient.AuthType)); return String.Empty; // Error, no valid digest challenge, no further processing required } // now make sure there's nothing at the end of the challenge that is not part of the digest challenge // this would happen if I have a Digest challenge followed by another challenge like ",NTLM,Negotiate" // use this DCR when avaialble to do this without parsing: // 762116 2 WDigest should ignore directives that do not have a value int startingPoint = 0; int start = startingPoint; int offset; bool valid = true; string name, value; HttpDigestChallenge digestChallenge = new HttpDigestChallenge(); for (;;) { offset = start; index = AuthenticationManager.SplitNoQuotes(incoming, ref offset); GlobalLog.Print("DigestClient::XPDoAuthenticate() SplitNoQuotes() returning index:" + index + " offset:" + offset); if (offset<0) { break; } name = incoming.Substring(start, offset-start); if (index<0) { value = HttpDigest.unquote(incoming.Substring(offset+1)); } else { value = HttpDigest.unquote(incoming.Substring(offset+1, index-offset-1)); } valid = digestChallenge.defineAttribute(name, value); GlobalLog.Print("DigestClient::XPDoAuthenticate() defineAttribute(" + name + ", " + value + ") returns " + valid); if (index<0 || !valid) { break; } start = ++index; } GlobalLog.Print("DigestClient::XPDoAuthenticate() start:" + start + " offset:" + offset + " index:" + index + " valid:" + valid + " incoming.Length:" + incoming.Length + " incoming:" + incoming); if ((!valid || offset<0) && start<incoming.Length) { incoming = start > 0 ? incoming.Substring(0, start-1) : ""; // First parameter might have been invalid, leaving start at 0 } return incoming; } } internal class HttpDigestChallenge { // General authentication related information internal string HostName; internal string Realm; internal Uri ChallengedUri; // Digest specific fields internal string Uri; internal string Nonce; internal string Opaque; internal bool Stale; internal string Algorithm; internal string Method; internal string Domain; internal string QualityOfProtection; internal string ClientNonce; internal int NonceCount; internal string Charset; internal string ServiceName; internal string ChannelBinding; internal bool UTF8Charset; internal bool QopPresent; internal MD5CryptoServiceProvider MD5provider = new MD5CryptoServiceProvider(); internal void SetFromRequest(HttpWebRequest httpWebRequest) { this.HostName = httpWebRequest.ChallengedUri.Host; this.Method = httpWebRequest.CurrentMethod.Name; if (httpWebRequest.CurrentMethod.ConnectRequest) { // Use the orriginal request Uri, not the proxy Uri this.Uri = httpWebRequest.RequestUri.GetParts(UriComponents.HostAndPort, UriFormat.UriEscaped); } else { // Don't use PathAndQuery, it breaks IIS6 // GetParts(Path) doesn't return the initial slash this.Uri = "/" + httpWebRequest.GetRemoteResourceUri().GetParts(UriComponents.Path, UriFormat.UriEscaped); } this.ChallengedUri = httpWebRequest.ChallengedUri; } internal HttpDigestChallenge CopyAndIncrementNonce() { HttpDigestChallenge challengeCopy = null; lock(this) { challengeCopy = this.MemberwiseClone() as HttpDigestChallenge; ++NonceCount; } challengeCopy.MD5provider = new MD5CryptoServiceProvider(); return challengeCopy; } public bool defineAttribute(string name, string value) { name = name.Trim().ToLower(CultureInfo.InvariantCulture); if (name.Equals(HttpDigest.DA_algorithm)) { Algorithm = value; } else if (name.Equals(HttpDigest.DA_cnonce)) { ClientNonce = value; } else if (name.Equals(HttpDigest.DA_nc)) { NonceCount = Int32.Parse(value, NumberFormatInfo.InvariantInfo); } else if (name.Equals(HttpDigest.DA_nonce)) { Nonce = value; } else if (name.Equals(HttpDigest.DA_opaque)) { Opaque = value; } else if (name.Equals(HttpDigest.DA_qop)) { QualityOfProtection = value; QopPresent = QualityOfProtection!=null && QualityOfProtection.Length>0; } else if (name.Equals(HttpDigest.DA_realm)) { Realm = value; } else if (name.Equals(HttpDigest.DA_domain)) { Domain = value; } else if (name.Equals(HttpDigest.DA_response)) { } else if (name.Equals(HttpDigest.DA_stale)) { Stale = value.ToLower(CultureInfo.InvariantCulture).Equals("true"); } else if (name.Equals(HttpDigest.DA_uri)) { Uri = value; } else if (name.Equals(HttpDigest.DA_charset)) { Charset = value; } else if (name.Equals(HttpDigest.DA_cipher)) { // ignore } else if (name.Equals(HttpDigest.DA_username)) { // ignore } else { // // the token is not recognized, this usually // happens when there are multiple challenges // return false; } return true; } internal string ToBlob() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_realm, Realm, true)); if (Algorithm!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_algorithm, Algorithm, true)); } if (Charset!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_charset, Charset, false)); } if (Nonce!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_nonce, Nonce, true)); } if (Uri!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_uri, Uri, true)); } if (ClientNonce!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_cnonce, ClientNonce, true)); } if (NonceCount>0) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_nc, NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo), true)); } if (QualityOfProtection!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_qop, QualityOfProtection, true)); } if (Opaque!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_opaque, Opaque, true)); } if (Domain!=null) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_domain, Domain, true)); } if (Stale) { stringBuilder.Append(","); stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_stale, "true", true)); } return stringBuilder.ToString(); } } internal static class HttpDigest { // // these are the tokens defined by Digest // http://www.ietf.org/rfc/rfc2831.txt // internal const string DA_algorithm = "algorithm"; internal const string DA_cnonce = "cnonce"; // client-nonce internal const string DA_domain = "domain"; internal const string DA_nc = "nc"; // nonce-count internal const string DA_nonce = "nonce"; internal const string DA_opaque = "opaque"; internal const string DA_qop = "qop"; // quality-of-protection internal const string DA_realm = "realm"; internal const string DA_response = "response"; internal const string DA_stale = "stale"; internal const string DA_uri = "uri"; internal const string DA_username = "username"; internal const string DA_charset = "charset"; internal const string DA_cipher = "cipher"; // directives specific to CBT. hashed-dirs contains a comma-separated list of directives // that have been hashed into the client nonce. service-name contains the client-provided // SPN. channel-binding contains the hex-encoded MD5 hash of the channel binding token. internal const string DA_hasheddirs = "hashed-dirs"; internal const string DA_servicename = "service-name"; internal const string DA_channelbinding = "channel-binding"; internal const string SupportedQuality = "auth"; internal const string ValidSeparator = ", \"\'\t\r\n"; // The value of the hashed-dirs directive. It's always "service-name,channel-binding". internal const string HashedDirs = DA_servicename + "," + DA_channelbinding; // A server which understands CBT will send a nonce with this prefix. If we see it, // send a response containing the CBT directives. internal const string Upgraded = "+Upgraded+"; // When sending an upgraded response, we prefix this string to the client-nonce directive // to let the server know. internal const string UpgradedV1 = Upgraded + "v1"; // If the client application doesn't provide a ChannelBinding, this is what we send // as the channel-binding directive, meaning that the client had no outer secure channel. // See ZeroBindHash in ds/security/protocols/sspcommon/sspbindings.cxx internal const string ZeroChannelBindingHash = "00000000000000000000000000000000"; private const string suppressExtendedProtectionKey = @"System\CurrentControlSet\Control\Lsa"; private const string suppressExtendedProtectionKeyPath = @"HKEY_LOCAL_MACHINE\" + suppressExtendedProtectionKey; private const string suppressExtendedProtectionValueName = "SuppressExtendedProtection"; private static volatile bool suppressExtendedProtection; static HttpDigest() { ReadSuppressExtendedProtectionRegistryValue(); } [RegistryPermission(SecurityAction.Assert, Read = suppressExtendedProtectionKeyPath)] private static void ReadSuppressExtendedProtectionRegistryValue() { // In Win7 and later, the default value for SuppressExtendedProtection is 0 (enable // CBT support), whereas in pre-Win7 OS versions it is 1 (suppress CBT support). suppressExtendedProtection = !ComNetOS.IsWin7orLater; try { using (RegistryKey lsaKey = Registry.LocalMachine.OpenSubKey(suppressExtendedProtectionKey)) { try { // We only consider value 1 (2 is only used for Kerberos and 0 means CBT should // be supported). We ignore all other values. if (lsaKey.GetValueKind(suppressExtendedProtectionValueName) == RegistryValueKind.DWord) { suppressExtendedProtection = ((int)lsaKey.GetValue(suppressExtendedProtectionValueName)) == 1; } } catch (UnauthorizedAccessException e) { if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message); } catch (IOException e) { if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message); } } } catch (SecurityException e) { if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message); } catch (ObjectDisposedException e) { if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message); } } // // consider internally caching the nonces sent to us by a server so that // we can correctly send out nonce counts for subsequent requests // // used to create a random nonce // private static readonly RNGCryptoServiceProvider RandomGenerator = new RNGCryptoServiceProvider(); // // this method parses the challenge and breaks it into the // fundamental pieces that Digest defines and understands // internal static HttpDigestChallenge Interpret(string challenge, int startingPoint, HttpWebRequest httpWebRequest) { HttpDigestChallenge digestChallenge = new HttpDigestChallenge(); digestChallenge.SetFromRequest(httpWebRequest); // // define the part of the challenge we really care about // startingPoint = startingPoint==-1 ? 0 : startingPoint + DigestClient.SignatureSize; bool valid; int start, offset, index; string name, value; // forst time parse looking for a charset="utf-8" directive // not too bad, IIS 6.0, by default, sends this as the first directive. // if the server does not send this we'll end up parsing twice. start = startingPoint; for (;;) { offset = start; index = AuthenticationManager.SplitNoQuotes(challenge, ref offset); if (offset<0) { break; } name = challenge.Substring(start, offset-start); if (string.Compare(name, DA_charset, StringComparison.OrdinalIgnoreCase)==0) { if (index<0) { value = unquote(challenge.Substring(offset+1)); } else { value = unquote(challenge.Substring(offset+1, index-offset-1)); } GlobalLog.Print("HttpDigest::Interpret() server provided a hint to use [" + value + "] encoding"); if (string.Compare(value, "utf-8", StringComparison.OrdinalIgnoreCase)==0) { digestChallenge.UTF8Charset = true; break; } } if (index<0) { break; } start = ++index; } // this time go through the directives, parse them and call defineAttribute() start = startingPoint; for (;;) { offset = start; index = AuthenticationManager.SplitNoQuotes(challenge, ref offset); GlobalLog.Print("HttpDigest::Interpret() SplitNoQuotes() returning index:" + index.ToString() + " offset:" + offset.ToString()); if (offset<0) { break; } name = challenge.Substring(start, offset-start); if (index<0) { value = unquote(challenge.Substring(offset+1)); } else { value = unquote(challenge.Substring(offset+1, index-offset-1)); } if (digestChallenge.UTF8Charset) { bool isAscii = true; for (int i=0; i<value.Length; i++) { if (value[i]>(char)0x7F) { isAscii = false; break; } } if (!isAscii) { GlobalLog.Print("HttpDigest::Interpret() UTF8 decoding required value:[" + value + "]"); byte[] bytes = new byte[value.Length]; for (int i=0; i<value.Length; i++) { bytes[i] = (byte)value[i]; } value = Encoding.UTF8.GetString(bytes); GlobalLog.Print("HttpDigest::Interpret() UTF8 decoded value:[" + value + "]"); } else { GlobalLog.Print("HttpDigest::Interpret() no need for special encoding"); } } valid = digestChallenge.defineAttribute(name, value); GlobalLog.Print("HttpDigest::Interpret() defineAttribute(" + name + ", " + value + ") returns " + valid.ToString()); if (index<0 || !valid) { break; } start = ++index; } // We must absolutely have a nonce for Digest to work. if (digestChallenge.Nonce == null) { if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_digest_requires_nonce)); return null; } return digestChallenge; } private enum Charset { ASCII, ANSI, UTF8 } private static string CharsetEncode(string rawString, Charset charset) { #if TRAVE GlobalLog.Print("HttpDigest::CharsetEncode() encoding rawString:[" + rawString + "] Chars(rawString):[" + Chars(rawString) + "] charset:[" + charset + "]"); #endif // #if TRAVE if (charset==Charset.UTF8 || charset==Charset.ANSI) { byte[] bytes = charset==Charset.UTF8 ? Encoding.UTF8.GetBytes(rawString) : Encoding.Default.GetBytes(rawString); // the following code is the same as: // rawString = Encoding.Default.GetString(bytes); // but it's faster. char[] chars = new char[bytes.Length]; bytes.CopyTo(chars, 0); rawString = new string(chars); } #if TRAVE GlobalLog.Print("HttpDigest::CharsetEncode() encoded rawString:[" + rawString + "] Chars(rawString):[" + Chars(rawString) + "] charset:[" + charset + "]"); #endif // #if TRAVE return rawString; } private static Charset DetectCharset(string rawString) { Charset charset = Charset.ASCII; for (int i=0; i<rawString.Length; i++) { if (rawString[i]>(char)0x7F) { GlobalLog.Print("HttpDigest::DetectCharset() found non ASCII character:[" + ((int)rawString[i]).ToString() + "] at offset i:[" + i.ToString() + "] charset:[" + charset.ToString() + "]"); // ----, but the only way we can tell if we can use default ANSI encoding is see // in the encode/decode process there is no loss of information. byte[] bytes = Encoding.Default.GetBytes(rawString); string rawCopy = Encoding.Default.GetString(bytes); charset = string.Compare(rawString, rawCopy, StringComparison.Ordinal)==0 ? Charset.ANSI : Charset.UTF8; break; } } GlobalLog.Print("HttpDigest::DetectCharset() rawString:[" + rawString + "] has charset:[" + charset.ToString() + "]"); return charset; } #if TRAVE private static string Chars(string rawString) { string returnString = "["; for (int i=0; i<rawString.Length; i++) { if (i>0) { returnString += ","; } returnString += ((int)rawString[i]).ToString(); } return returnString + "]"; } #endif // #if TRAVE // // CONSIDER V.NEXT // creating a static hashtable for server nonces and keep track of nonce count // internal static Authorization Authenticate(HttpDigestChallenge digestChallenge, NetworkCredential NC, string spn, ChannelBinding binding) { string username = NC.InternalGetUserName(); if (ValidationHelper.IsBlankString(username)) { return null; } string password = NC.InternalGetPassword(); bool upgraded = IsUpgraded(digestChallenge.Nonce, binding); if (upgraded) { digestChallenge.ServiceName = spn; digestChallenge.ChannelBinding = hashChannelBinding(binding, digestChallenge.MD5provider); } if (digestChallenge.QopPresent) { if (digestChallenge.ClientNonce==null || digestChallenge.Stale) { GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, need new nonce. digestChallenge.ClientNonce:" + ValidationHelper.ToString(digestChallenge.ClientNonce) + " digestChallenge.Stale:" + digestChallenge.Stale.ToString()); if (upgraded) { digestChallenge.ClientNonce = createUpgradedNonce(digestChallenge); } else { digestChallenge.ClientNonce = createNonce(32); } digestChallenge.NonceCount = 1; } else { GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, reusing nonce. digestChallenge.NonceCount:" + digestChallenge.NonceCount.ToString()); digestChallenge.NonceCount++; } } StringBuilder authorization = new StringBuilder(); // // look at username & password, if it's not ASCII we need to attempt some // kind of encoding because we need to calculate the hash on byte[] // Charset usernameCharset = DetectCharset(username); if (!digestChallenge.UTF8Charset && usernameCharset==Charset.UTF8) { GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE username. failing auth."); return null; } Charset passwordCharset = DetectCharset(password); if (!digestChallenge.UTF8Charset && passwordCharset==Charset.UTF8) { GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE password. failing auth."); return null; } if (digestChallenge.UTF8Charset) { // on the wire always use UTF8 when the server supports it authorization.Append(pair(DA_charset, "utf-8", false)); authorization.Append(","); if (usernameCharset==Charset.UTF8) { username = CharsetEncode(username, Charset.UTF8); authorization.Append(pair(DA_username, username, true)); authorization.Append(","); } else { authorization.Append(pair(DA_username, CharsetEncode(username, Charset.UTF8), true)); authorization.Append(","); username = CharsetEncode(username, usernameCharset); } } else { // otherwise UTF8 is not required username = CharsetEncode(username, usernameCharset); authorization.Append(pair(DA_username, username, true)); authorization.Append(","); } password = CharsetEncode(password, passwordCharset); // no special encoding for the realm since we're just going to echo it back (encoding must have happened on the server). authorization.Append(pair(DA_realm, digestChallenge.Realm, true)); authorization.Append(","); authorization.Append(pair(DA_nonce, digestChallenge.Nonce, true)); authorization.Append(","); authorization.Append(pair(DA_uri, digestChallenge.Uri, true)); if (digestChallenge.QopPresent) { if (digestChallenge.Algorithm!=null) { // consider: should we default to "MD5" here? IE does authorization.Append(","); authorization.Append(pair(DA_algorithm, digestChallenge.Algorithm, true)); // IE sends quotes - IIS needs them } authorization.Append(","); authorization.Append(pair(DA_cnonce, digestChallenge.ClientNonce, true)); authorization.Append(","); authorization.Append(pair(DA_nc, digestChallenge.NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo), false)); // RAID#47397 // send only the QualityOfProtection we're using // since we support only "auth" that's what we will send out authorization.Append(","); authorization.Append(pair(DA_qop, SupportedQuality, true)); // IE sends quotes - IIS needs them if (upgraded) { authorization.Append(","); authorization.Append(pair(DA_hasheddirs, HashedDirs, true)); authorization.Append(","); authorization.Append(pair(DA_servicename, digestChallenge.ServiceName, true)); authorization.Append(","); authorization.Append(pair(DA_channelbinding, digestChallenge.ChannelBinding, true)); } } // warning: this must be computed here string responseValue = HttpDigest.responseValue(digestChallenge, username, password); if (responseValue==null) { return null; } authorization.Append(","); authorization.Append(pair(DA_response, responseValue, true)); // IE sends quotes - IIS needs them if (digestChallenge.Opaque!=null) { authorization.Append(","); authorization.Append(pair(DA_opaque, digestChallenge.Opaque, true)); } GlobalLog.Print("HttpDigest::Authenticate() digestChallenge.Stale:" + digestChallenge.Stale.ToString()); // completion is decided in Update() Authorization finalAuthorization = new Authorization(DigestClient.AuthType + " " + authorization.ToString(), false); return finalAuthorization; } private static bool IsUpgraded(string nonce, ChannelBinding binding) { GlobalLog.Assert(nonce != null, "HttpDigest::IsUpgraded()|'nonce' must not be null."); // Digest-SSP ignores the SuppressExtendedProtection Registry value, if the the caller // passes a channel binding. I.e. we must consider SuppressExtendedProtection only if // there is no channel binding (e.g. in the http:// case). if ((binding == null) && (suppressExtendedProtection)) { return false; } // Extended Protection is only possible if both the SSPs on the current system support // EP and the server sent a 'nonce' containing the +Upgraded+ prefix. return AuthenticationManager.SspSupportsExtendedProtection && nonce.StartsWith(Upgraded, StringComparison.Ordinal); } internal static string unquote(string quotedString) { return quotedString.Trim().Trim("\"".ToCharArray()); } // Returns the string consisting of <name> followed by // an equal sign, followed by the <value> in double-quotes internal static string pair(string name, string value, bool quote) { if (quote) { return name + "=\"" + value + "\""; } return name + "=" + value; } // // this method computes the response-value according to the // rules described in RFC2831 section 2.1.2.1 // private static string responseValue(HttpDigestChallenge challenge, string username, string password) { string secretString = computeSecret(challenge, username, password); if (secretString == null) { return null; } // we assume auth here, since it's the only one we support, the check happened earlier string dataString = challenge.Method + ":" + challenge.Uri; if (dataString == null) { return null; } string secret = hashString(secretString, challenge.MD5provider); string hexMD2 = hashString(dataString, challenge.MD5provider); string data = challenge.Nonce + ":" + (challenge.QopPresent ? challenge.NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo) + ":" + challenge.ClientNonce + ":" + SupportedQuality + ":" + // challenge.QualityOfProtection + ":" + hexMD2 : hexMD2); return hashString(secret + ":" + data, challenge.MD5provider); } private static string computeSecret(HttpDigestChallenge challenge, string username, string password) { if (challenge.Algorithm==null || string.Compare(challenge.Algorithm, "md5" ,StringComparison.OrdinalIgnoreCase)==0) { return username + ":" + challenge.Realm + ":" + password; } else if (string.Compare(challenge.Algorithm, "md5-sess" ,StringComparison.OrdinalIgnoreCase)==0) { return hashString(username + ":" + challenge.Realm + ":" + password, challenge.MD5provider) + ":" + challenge.Nonce + ":" + challenge.ClientNonce; } if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_digest_hash_algorithm_not_supported, challenge.Algorithm)); return null; } // Where in the SecChannelBindings struct to find these fields private static int InitiatorTypeOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "dwInitiatorAddrType"); private static int InitiatorLengthOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "cbInitiatorLength"); private static int InitiatorOffsetOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "dwInitiatorOffset"); private static int AcceptorTypeOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "dwAcceptorAddrType"); private static int AcceptorLengthOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "cbAcceptorLength"); private static int AcceptorOffsetOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "dwAcceptorOffset"); private static int ApplicationDataLengthOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "cbApplicationDataLength"); private static int ApplicationDataOffsetOffset = (int)Marshal.OffsetOf(typeof(SecChannelBindings), "dwApplicationDataOffset"); private static int SizeOfInt = Marshal.SizeOf(typeof(int)); private static int MinimumFormattedBindingLength = 5 * SizeOfInt; // // Adapted from ComputeGssBindHash() in ds\security\protocols\sspcommon\sspbindings.cxx // // The formatted binding is: // 1. the initiator type and length // 2. the initiator data, if any // 3. the acceptor type and length // 4. the acceptor data, if any // 5. the application data length // 6. the application data, if any // private static byte[] formatChannelBindingForHash(ChannelBinding binding) { int initiatorType = Marshal.ReadInt32(binding.DangerousGetHandle(), InitiatorTypeOffset); int initiatorLength = Marshal.ReadInt32(binding.DangerousGetHandle(), InitiatorLengthOffset); int acceptorType = Marshal.ReadInt32(binding.DangerousGetHandle(), AcceptorTypeOffset); int acceptorLength = Marshal.ReadInt32(binding.DangerousGetHandle(), AcceptorLengthOffset); int applicationDataLength = Marshal.ReadInt32(binding.DangerousGetHandle(), ApplicationDataLengthOffset); byte[] formattedData = new byte[MinimumFormattedBindingLength + initiatorLength + acceptorLength + applicationDataLength]; BitConverter.GetBytes(initiatorType).CopyTo(formattedData, 0); BitConverter.GetBytes(initiatorLength).CopyTo(formattedData, SizeOfInt); int offset = 2 * SizeOfInt; if (initiatorLength > 0) { int initiatorOffset = Marshal.ReadInt32(binding.DangerousGetHandle(), InitiatorOffsetOffset); Marshal.Copy(IntPtrHelper.Add(binding.DangerousGetHandle(), initiatorOffset), formattedData, offset, initiatorLength); offset += initiatorLength; } BitConverter.GetBytes(acceptorType).CopyTo(formattedData, offset); BitConverter.GetBytes(acceptorLength).CopyTo(formattedData, offset + SizeOfInt); offset += 2 * SizeOfInt; if (acceptorLength > 0) { int acceptorOffset = Marshal.ReadInt32(binding.DangerousGetHandle(), AcceptorOffsetOffset); Marshal.Copy(IntPtrHelper.Add(binding.DangerousGetHandle(), acceptorOffset), formattedData, offset, acceptorLength); offset += acceptorLength; } BitConverter.GetBytes(applicationDataLength).CopyTo(formattedData, offset); offset += SizeOfInt; if (applicationDataLength > 0) { int applicationDataOffset = Marshal.ReadInt32(binding.DangerousGetHandle(), ApplicationDataOffsetOffset); Marshal.Copy(IntPtrHelper.Add(binding.DangerousGetHandle(), applicationDataOffset), formattedData, offset, applicationDataLength); } return formattedData; } private static string hashChannelBinding(ChannelBinding binding, MD5CryptoServiceProvider MD5provider) { if (binding == null) { return ZeroChannelBindingHash; } byte[] formattedData = formatChannelBindingForHash(binding); byte[] hash = MD5provider.ComputeHash(formattedData); return hexEncode(hash); } private static string hashString(string myString, MD5CryptoServiceProvider MD5provider) { GlobalLog.Enter("HttpDigest::hashString", "[" + myString.Length.ToString() + ":" + myString + "]"); byte[] encodedBytes = new byte[myString.Length]; for (int i=0; i<myString.Length; i++) { encodedBytes[i] = (byte)myString[i]; } byte[] hash = MD5provider.ComputeHash(encodedBytes); string hashString = hexEncode(hash); GlobalLog.Leave("HttpDigest::hashString", "[" + hashString.Length.ToString() + ":" + hashString + "]"); return hashString; } private static string hexEncode(byte[] rawbytes) { int size = rawbytes.Length; char[] wa = new char[2*size]; for (int i=0, dp=0; i<size; i++) { // warning: these ARE case sensitive wa[dp++] = Uri.HexLowerChars[rawbytes[i]>>4]; wa[dp++] = Uri.HexLowerChars[rawbytes[i]&0x0F]; } return new string(wa); } /* returns a random nonce of given length */ private static string createNonce(int length) { // we'd need less (half of that), but this makes the code much simpler int bytesNeeded = length; byte[] randomBytes = new byte[bytesNeeded]; char[] digits = new char[length]; RandomGenerator.GetBytes(randomBytes); for (int i=0; i<length; i++) { // warning: these ARE case sensitive digits[i] = Uri.HexLowerChars[randomBytes[i]&0x0F]; } return new string(digits); } private static string createUpgradedNonce(HttpDigestChallenge digestChallenge) { string hashMe = digestChallenge.ServiceName + ":" + digestChallenge.ChannelBinding; byte[] hash = digestChallenge.MD5provider.ComputeHash(Encoding.ASCII.GetBytes(hashMe)); return UpgradedV1 + hexEncode(hash) + createNonce(32); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; namespace PulseWaveAnalyzer.model { public static class DBParser { public const string version = "J.Y.Liu 2012"; public const string path = ""; // @"C:\Users\J.Y.Liu\Desktop\thesis\AHTCM\"; /* * medicine.bin * medicine table->id, name, mild, (ht,lr,ki,sp,lu,st,gb,bl,li,tb,si,pc) */ public const string medicineDBName = path + "medicine.bin"; /* * prescript.bin * prescript table->id, name, prescript * > prescript format: medicine id,weight,state; */ public const string prescriptDBName = path + "prescript.bin"; private static DBConnector db = new DBConnector(); public static List<Medicine> medicineDB() { DataTable dt; db.open(medicineDBName); db.prepare("select * from [medicine] order by [id]"); dt = db.query(); db.close(); if (dt == null) return null; if (dt.Rows == null) return null; List<Medicine> list = new List<Medicine>(); foreach (DataRow x in dt.Rows) list.Add(convertToMedicine(x)); list.Sort(); return list; } private static Medicine convertToMedicine(DataRow dr) { if (dr == null) return null; Medicine m = new Medicine(); m.id = int.Parse(dr["id"].ToString()); m.name = dr["name"].ToString(); m.mild = double.Parse(dr["mild"].ToString()); m.merdian[0] = double.Parse(dr["ht"].ToString()); m.merdian[1] = double.Parse(dr["lr"].ToString()); m.merdian[2] = double.Parse(dr["ki"].ToString()); m.merdian[3] = double.Parse(dr["sp"].ToString()); m.merdian[4] = double.Parse(dr["lu"].ToString()); m.merdian[5] = double.Parse(dr["st"].ToString()); m.merdian[6] = double.Parse(dr["gb"].ToString()); m.merdian[7] = double.Parse(dr["bl"].ToString()); m.merdian[8] = double.Parse(dr["li"].ToString()); m.merdian[9] = double.Parse(dr["tb"].ToString()); m.merdian[10] = double.Parse(dr["si"].ToString()); m.merdian[11] = double.Parse(dr["pc"].ToString()); return m; } public static List<Prescript> prescriptDB(List<Medicine> medsdb) { if (medsdb == null) return null; DataTable dt; db.open(prescriptDBName); db.prepare("select * from [prescript]"); dt = db.query(); db.close(); if (dt == null) return null; if (dt.Rows == null) return null; List<Prescript> list = new List<Prescript>(); foreach (DataRow x in dt.Rows) list.Add(convertToPrescript(medsdb, x)); list.Sort(); return list; } private static Prescript convertToPrescript(List<Medicine> medsdb, DataRow dr) { if (dr == null) return null; Prescript p = new Prescript(); p.id = int.Parse(dr["id"].ToString()); p.name = dr["name"].ToString(); string prescriptline = dr["prescript"].ToString(); if (prescriptline == null) return null; string[] medicines = prescriptline.Split(";".ToCharArray()); string[] para; int id; double weight, state; Medicine mmm = new Medicine(); foreach (string x in medicines) { if (x.Length == 0) continue; para = x.Split(",".ToCharArray()); id = int.Parse(para[0]); weight = double.Parse(para[1]); state = double.Parse(para[2]); mmm.id = id; id = medsdb.BinarySearch(mmm); if(id==-1) continue; p.add(medsdb[id], weight, state); } p.sort(); return p; } public static void removeMedicine(int id) { db.open(medicineDBName); db.prepare("delete from [medicine] where [id]="+id); db.update(); db.close(); } public static void removePrescript(int id) { db.open(prescriptDBName); db.prepare("delete from [prescript] where [id]=" + id); db.update(); db.close(); } public static void addMedicine(List<Medicine> mlist, Medicine m) { int index = mlist.BinarySearch(m); if (index < 0) { db.open(medicineDBName); db.prepare("insert into [medicine] values (null,'" + m.name + "'," + m.mild + "," + m.merdian[0] + "," + m.merdian[1] + "," + m.merdian[2] + "," + m.merdian[3] + "," + m.merdian[4] + "," + m.merdian[5] + "," + m.merdian[6] + "," + m.merdian[7] + "," + m.merdian[8] + "," + m.merdian[9] + "," + m.merdian[10] + "," + m.merdian[11] + ")"); db.update(); db.prepare("select last_insert_rowid()"); DataTable dt = db.query(); db.close(); if (dt.Rows.Count > 0) { int lastid = int.Parse(dt.Rows[0][0].ToString()); m.id = lastid; //mlist.Add(m); } } } public static void addPrescript(List<Prescript> plist, Prescript p) { int index = plist.BinarySearch(p); if (index < 0) { db.open(prescriptDBName); db.prepare("insert into [prescript] values (null,'" + p.name + "','" + p.toPrescriptString() + "')"); db.update(); db.prepare("select last_insert_rowid()"); DataTable dt = db.query(); db.close(); if (dt.Rows.Count > 0) { int lastid = int.Parse(dt.Rows[0][0].ToString()); p.id = lastid; //plist.Add(p); } } } public static void updateMedicine(Medicine m) { db.open(medicineDBName); db.prepare("update [medicine] set [name]=@name,[mild]=@mild,[ht]=@ht,[lr]=@lr,[ki]=@ki,[sp]=@sp,[lu]=@lu,[st]=@st,[gb]=@gb,[bl]=@bl,[li]=@li,[tb]=@tb,[si]=@si,[pc]=@pc where [id]=@id"); db.setup(DbType.String, "name", m.name); db.setup(DbType.Double, "mild", m.mild); db.setup(DbType.Double, "ht", m.merdian[0]); db.setup(DbType.Double, "lr", m.merdian[1]); db.setup(DbType.Double, "ki", m.merdian[2]); db.setup(DbType.Double, "sp", m.merdian[3]); db.setup(DbType.Double, "lu", m.merdian[4]); db.setup(DbType.Double, "st", m.merdian[5]); db.setup(DbType.Double, "gb", m.merdian[6]); db.setup(DbType.Double, "bl", m.merdian[7]); db.setup(DbType.Double, "li", m.merdian[8]); db.setup(DbType.Double, "tb", m.merdian[9]); db.setup(DbType.Double, "si", m.merdian[10]); db.setup(DbType.Double, "pc", m.merdian[11]); db.setup(DbType.Int32, "id", m.id); db.update(); db.close(); } public static void updatePrescript(Prescript p) { db.open(prescriptDBName); db.prepare("update [prescript] set [name]=@name,[prescript]=@script where [id]=@id"); db.setup(DbType.String, "name", p.name); db.setup(DbType.String, "script", p.toPrescriptString()); db.setup(DbType.Int32, "id", p.id); db.update(); db.close(); } public static List<Prescript> getRelatedPrescript(List<Prescript> plist, Medicine m) { List<Prescript> ps = new List<Prescript>(); foreach (Prescript x in plist) { if (x.indexOf(m) >= 0) ps.Add(x); } return ps; } } }
using System; using System.Collections.Generic; using System.Messaging; using System.Runtime.Serialization; using System.Transactions; using log4net; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Msmq.TransportActions; using Rhino.ServiceBus.Transport; using Rhino.ServiceBus.Util; using MessageType=Rhino.ServiceBus.Transport.MessageType; namespace Rhino.ServiceBus.Msmq { public class MsmqTransport : AbstractMsmqListener, IMsmqTransport { [ThreadStatic] private static MsmqCurrentMessageInformation currentMessageInformation; public static MsmqCurrentMessageInformation MsmqCurrentMessageInformation { get { return currentMessageInformation; } } public CurrentMessageInformation CurrentMessageInformation { get { return currentMessageInformation; } } private readonly ILog logger = LogManager.GetLogger(typeof(MsmqTransport)); private readonly IMsmqTransportAction[] transportActions; private readonly IsolationLevel queueIsolationLevel; private readonly bool consumeInTransaction; public MsmqTransport(IMessageSerializer serializer, IQueueStrategy queueStrategy, Uri endpoint, int threadCount, IMsmqTransportAction[] transportActions, IEndpointRouter endpointRouter, IsolationLevel queueIsolationLevel, TransactionalOptions transactional, bool consumeInTransaction, IMessageBuilder<Message> messageBuilder) : base(queueStrategy, endpoint, threadCount, serializer, endpointRouter, transactional, messageBuilder) { this.transportActions = transportActions; this.queueIsolationLevel = queueIsolationLevel; this.consumeInTransaction = consumeInTransaction; } #region ITransport Members protected override void BeforeStart(OpenedQueue queue) { foreach (var messageAction in transportActions) { messageAction.Init(this, queue); } } public void Reply(params object[] messages) { if (currentMessageInformation == null) throw new TransactionException("There is no message to reply to, sorry."); logger.DebugFormat("Replying to {0}", currentMessageInformation.Source); Send(endpointRouter.GetRoutedEndpoint(currentMessageInformation.Source), messages); } public event Action<CurrentMessageInformation> MessageSent; public event Func<CurrentMessageInformation, bool> AdministrativeMessageArrived; public event Func<CurrentMessageInformation, bool> MessageArrived; public event Action<CurrentMessageInformation, Exception> MessageProcessingFailure; public event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted; public event Action<CurrentMessageInformation> BeforeMessageTransactionCommit; public event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted; public void Discard(object msg) { var message = GenerateMsmqMessageFromMessageBatch(new[] { msg }); SendMessageToQueue(message.SetSubQueueToSendTo(SubQueue.Discarded), Endpoint); } public bool RaiseAdministrativeMessageArrived(CurrentMessageInformation information) { var copy = AdministrativeMessageArrived; if (copy != null) return copy(information); return false; } public void RaiseAdministrativeMessageProcessingCompleted(CurrentMessageInformation information, Exception ex) { var copy = AdministrativeMessageProcessingCompleted; if (copy != null) copy(information, ex); } public void Send(Endpoint endpoint, DateTime processAgainAt, object[] msgs) { if (HaveStarted == false) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); var processAgainBytes = BitConverter.GetBytes(processAgainAt.ToBinary()); if (message.Extension.Length == 16) { var bytes = new List<byte>(message.Extension); bytes.AddRange(processAgainBytes); message.Extension = bytes.ToArray(); } else { var extension = (byte[])message.Extension.Clone(); Buffer.BlockCopy(processAgainBytes, 0, extension, 16, processAgainBytes.Length); message.Extension = extension; } message.AppSpecific = (int)MessageType.TimeoutMessageMarker; SendMessageToQueue(message, endpoint); } public void Send(Endpoint destination, object[] msgs) { if(HaveStarted==false) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); SendMessageToQueue(message, destination); var copy = MessageSent; if (copy == null) return; copy(new CurrentMessageInformation { AllMessages = msgs, Source = Endpoint.Uri, Destination = destination.Uri, MessageId = message.GetMessageId(), }); } public event Action<CurrentMessageInformation, Exception> MessageSerializationException; #endregion public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted, Action<CurrentMessageInformation> beforeMessageTransactionCommit) { var transactionOptions = new TransactionOptions { IsolationLevel = queueIsolationLevel, Timeout = TransportUtil.GetTransactionTimeout(), }; using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return;// someone else got our message, better luck next time ProcessMessage(message, queue, tx, messageArrived, beforeMessageTransactionCommit, messageProcessingCompleted); } } private void ReceiveMessage(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return; ProcessMessage(message, queue, null, messageArrived, null, messageProcessingCompleted); } public void RaiseMessageSerializationException(OpenedQueue queue, Message msg, string errorMessage) { var copy = MessageSerializationException; if (copy == null) return; var messageInformation = new MsmqCurrentMessageInformation { MsmqMessage = msg, Queue = queue, Message = null, Source = queue.RootUri, MessageId = Guid.Empty }; copy(messageInformation, new SerializationException(errorMessage)); } public OpenedQueue CreateQueue() { return Endpoint.InitalizeQueue(); } private void ProcessMessage( Message message, OpenedQueue messageQueue, TransactionScope tx, Func<CurrentMessageInformation, bool> messageRecieved, Action<CurrentMessageInformation> beforeMessageTransactionCommit, Action<CurrentMessageInformation, Exception> messageCompleted) { Exception ex = null; currentMessageInformation = CreateMessageInformation(messageQueue, message, null, null); try { //deserialization errors do not count for module events object[] messages = DeserializeMessages(messageQueue, message, MessageSerializationException); try { foreach (object msg in messages) { currentMessageInformation = CreateMessageInformation(messageQueue, message, messages, msg); if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false) Discard(currentMessageInformation.Message); } } catch (Exception e) { ex = e; logger.Error("Failed to process message", e); } } catch (Exception e) { ex = e; logger.Error("Failed to deserialize message", e); } finally { Action sendMessageBackToQueue = null; if (message != null && (messageQueue.IsTransactional == false|| consumeInTransaction==false)) sendMessageBackToQueue = () => messageQueue.Send(message); var messageHandlingCompletion = new MessageHandlingCompletion(tx, sendMessageBackToQueue, ex, messageCompleted, beforeMessageTransactionCommit, logger, MessageProcessingFailure, currentMessageInformation); messageHandlingCompletion.HandleMessageCompletion(); currentMessageInformation = null; } } private MsmqCurrentMessageInformation CreateMessageInformation(OpenedQueue queue,Message message, object[] messages, object msg) { return new MsmqCurrentMessageInformation { MessageId = message.GetMessageId(), AllMessages = messages, Message = msg, Queue = queue, TransportMessageId = message.Id, Destination = Endpoint.Uri, Source = MsmqUtil.GetQueueUri(message.ResponseQueue), MsmqMessage = message, TransactionType = queue.GetTransactionType(), Headers = message.Extension.DeserializeHeaders() }; } private void SendMessageToQueue(Message message, Endpoint endpoint) { if (HaveStarted == false) throw new TransportException("Cannot send message before transport is started"); try { using (var sendQueue = MsmqUtil.GetQueuePath(endpoint).Open(QueueAccessMode.Send)) { sendQueue.Send(message); logger.DebugFormat("Send message {0} to {1}", message.Label, endpoint); } } catch (Exception e) { throw new TransactionException("Failed to send message to " + endpoint, e); } } protected override void HandlePeekedMessage(OpenedQueue queue,Message message) { foreach (var action in transportActions) { if(action.CanHandlePeekedMessage(message)==false) continue; try { if (action.HandlePeekedMessage(this, queue, message)) return; } catch (Exception e) { logger.Error("Error when trying to execute action " + action + " on message " + message.Id + ". Message has been removed without handling!", e); queue.ConsumeMessage(message.Id); } } if (consumeInTransaction) ReceiveMessageInTransaction(queue, message.Id, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit); else ReceiveMessage(queue, message.Id, MessageArrived, MessageProcessingCompleted); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnEnfermedade class. /// </summary> [Serializable] public partial class PnEnfermedadeCollection : ActiveList<PnEnfermedade, PnEnfermedadeCollection> { public PnEnfermedadeCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnEnfermedadeCollection</returns> public PnEnfermedadeCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnEnfermedade o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_enfermedades table. /// </summary> [Serializable] public partial class PnEnfermedade : ActiveRecord<PnEnfermedade>, IActiveRecord { #region .ctors and Default Settings public PnEnfermedade() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnEnfermedade(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnEnfermedade(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnEnfermedade(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_enfermedades", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema); colvarIdLegajo.ColumnName = "id_legajo"; colvarIdLegajo.DataType = DbType.Int32; colvarIdLegajo.MaxLength = 0; colvarIdLegajo.AutoIncrement = true; colvarIdLegajo.IsNullable = false; colvarIdLegajo.IsPrimaryKey = true; colvarIdLegajo.IsForeignKey = false; colvarIdLegajo.IsReadOnly = false; colvarIdLegajo.DefaultSetting = @""; colvarIdLegajo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLegajo); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = false; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarDiagnostico = new TableSchema.TableColumn(schema); colvarDiagnostico.ColumnName = "diagnostico"; colvarDiagnostico.DataType = DbType.AnsiString; colvarDiagnostico.MaxLength = -1; colvarDiagnostico.AutoIncrement = false; colvarDiagnostico.IsNullable = false; colvarDiagnostico.IsPrimaryKey = false; colvarDiagnostico.IsForeignKey = false; colvarDiagnostico.IsReadOnly = false; colvarDiagnostico.DefaultSetting = @""; colvarDiagnostico.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiagnostico); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_enfermedades",schema); } } #endregion #region Props [XmlAttribute("IdLegajo")] [Bindable(true)] public int IdLegajo { get { return GetColumnValue<int>(Columns.IdLegajo); } set { SetColumnValue(Columns.IdLegajo, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime Fecha { get { return GetColumnValue<DateTime>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("Diagnostico")] [Bindable(true)] public string Diagnostico { get { return GetColumnValue<string>(Columns.Diagnostico); } set { SetColumnValue(Columns.Diagnostico, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(DateTime varFecha,string varDiagnostico) { PnEnfermedade item = new PnEnfermedade(); item.Fecha = varFecha; item.Diagnostico = varDiagnostico; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdLegajo,DateTime varFecha,string varDiagnostico) { PnEnfermedade item = new PnEnfermedade(); item.IdLegajo = varIdLegajo; item.Fecha = varFecha; item.Diagnostico = varDiagnostico; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdLegajoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DiagnosticoColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdLegajo = @"id_legajo"; public static string Fecha = @"fecha"; public static string Diagnostico = @"diagnostico"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. [ComVisible(true)] public static partial class Path { // Platform specific alternate directory separator character. // There is only one directory separator char on Unix, which is the same // as the alternate separator on Windows, so same definition is used for both. public static readonly char AltDirectorySeparatorChar = '/'; // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any exsiting extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (path != null) { CheckInvalidPathChars(path); string normalizedPath = NormalizePath(path, fullCheck: false); // If there are no permissions for PathDiscovery to this path, we should NOT expand the short paths // as this would leak information about paths to which the user would not have access to. if (path.Length > 0) { try { // If we were passed in a path with \\?\ we need to remove it as FileIOPermission does not like it. string tempPath = RemoveLongPathPrefix(path); // FileIOPermission cannot handle paths that contain ? or * // So we only pass to FileIOPermission the text up to them. int pos = 0; while (pos < tempPath.Length && (tempPath[pos] != '?' && tempPath[pos] != '*')) pos++; // GetFullPath will Demand that we have the PathDiscovery FileIOPermission and thus throw // SecurityException if we don't. // While we don't use the result of this call we are using it as a consistent way of // doing the security checks. if (pos > 0) GetFullPath(tempPath.Substring(0, pos)); } catch (SecurityException) { // If the user did not have permissions to the path, make sure that we don't leak expanded short paths // Only re-normalize if the original path had a ~ in it. if (path.IndexOf("~", StringComparison.Ordinal) != -1) { normalizedPath = NormalizePath(path, fullCheck: false, expandShortPaths: false); } } catch (PathTooLongException) { } catch (NotSupportedException) { } // Security can throw this on "c:\foo:" catch (IOException) { } catch (ArgumentException) { } // The normalizePath with fullCheck will throw this for file: and http: } path = normalizedPath; int root = GetRootLength(path); int i = path.Length; if (i > root) { i = path.Length; if (i == root) return null; while (i > root && !IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } } return null; } public static char[] GetInvalidPathChars() { return (char[])InvalidPathChars.Clone(); } public static char[] GetInvalidFileNameChars() { return (char[])InvalidFileNameChars.Clone(); } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. [Pure] public static string GetExtension(string path) { if (path == null) return null; CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } private static string GetFullPathInternal(string path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return NormalizePath(path, fullCheck: true); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck) { return NormalizePath(path, fullCheck, MaxPath); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck, bool expandShortPaths) { return NormalizePath(path, fullCheck, MaxPath, expandShortPaths); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck, int maxPathLength) { return NormalizePath(path, fullCheck, maxPathLength, expandShortPaths: true); } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. [Pure] public static string GetFileName(string path) { if (path != null) { CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (IsDirectoryOrVolumeSeparator(ch)) return path.Substring(i + 1, length - i - 1); } } return path; } [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; path = GetFileName(path); int i; return (i = path.LastIndexOf('.')) == -1 ? path : // No path extension found path.Substring(0, i); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. [Pure] public static string GetPathRoot(string path) { if (path == null) return null; path = NormalizePath(path, fullCheck: false); return path.Substring(0, GetRootLength(path)); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static string GetRandomFileName() { // 5 bytes == 40 bits == 40/5 == 8 chars in our encoding. // So 10 bytes provides 16 chars, of which we need 11 // for the 8.3 name. byte[] key = CreateCryptoRandomByteArray(10); // rndCharArray is expected to be 16 chars char[] rndCharArray = ToBase32StringSuitableForDirName(key).ToCharArray(); rndCharArray[8] = '.'; return new string(rndCharArray, 0, 12); } // Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. [System.Security.SecuritySafeCritical] public static string GetTempFileName() { return InternalGetTempFileName(checkHost: true); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. [Pure] public static bool HasExtension(string path) { if (path != null) { CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? "path1" : "path2"); Contract.EndContractBlock(); CheckInvalidPathChars(path1); CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : "path3"); Contract.EndContractBlock(); CheckInvalidPathChars(path1); CheckInvalidPathChars(path2); CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException("paths"); } Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; // We have two passes, the first calcuates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException("paths"); } if (paths[i].Length == 0) { continue; } CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(DirectorySeparatorChar) .Append(path2) .Append(DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_Base32Char = { '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', '0', '1', '2', '3', '4', '5'}; private static string ToBase32StringSuitableForDirName(byte[] buff) { // This routine is optimised to be used with buffs of length 20 Debug.Assert(((buff.Length % 5) == 0), "Unexpected hash length"); // For every 5 bytes, 8 characters are appended. StringBuilder sb = StringBuilderCache.Acquire(); // Create l char for each of the last 5 bits of each byte. // Consume 3 MSB bits 5 bytes at a time. int len = buff.Length; int i = 0; do { byte b0 = (i < len) ? buff[i++] : (byte)0; byte b1 = (i < len) ? buff[i++] : (byte)0; byte b2 = (i < len) ? buff[i++] : (byte)0; byte b3 = (i < len) ? buff[i++] : (byte)0; byte b4 = (i < len) ? buff[i++] : (byte)0; // Consume the 5 Least significant bits of each byte sb.Append(s_Base32Char[b0 & 0x1F]); sb.Append(s_Base32Char[b1 & 0x1F]); sb.Append(s_Base32Char[b2 & 0x1F]); sb.Append(s_Base32Char[b3 & 0x1F]); sb.Append(s_Base32Char[b4 & 0x1F]); // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 sb.Append(s_Base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]); sb.Append(s_Base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]); // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; sb.Append(s_Base32Char[b2]); } while (i < len); return StringBuilderCache.GetStringAndRelease(sb); } private static bool HasIllegalCharacters(string path, bool checkAdditional) { Contract.Requires(path != null); return path.IndexOfAny(checkAdditional ? InvalidPathCharsWithAdditionalChecks : InvalidPathChars) >= 0; } private static void CheckInvalidPathChars(string path, bool checkAdditional = false) { Debug.Assert(path != null); if (HasIllegalCharacters(path, checkAdditional)) throw new ArgumentException(SR.Argument_InvalidPathChars, "path"); } } }
// 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.Security; using System.Text; using Internal.Runtime.CompilerServices; namespace System.Globalization { // needs to be kept in sync with CalendarDataType in System.Globalization.Native internal enum CalendarDataType { Uninitialized = 0, NativeName = 1, MonthDay = 2, ShortDates = 3, LongDates = 4, YearMonths = 5, DayNames = 6, AbbrevDayNames = 7, MonthNames = 8, AbbrevMonthNames = 9, SuperShortDayNames = 10, MonthGenitiveNames = 11, AbbrevMonthGenitiveNames = 12, EraNames = 13, AbbrevEraNames = 14, } internal partial class CalendarData { private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) { bool result = true; result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay); this.sMonthDay = NormalizeDatePattern(this.sMonthDay); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames); string leapHebrewMonthName = null; result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames, ref leapHebrewMonthName); if (leapHebrewMonthName != null) { // In Hebrew calendar, get the leap month name Adar II and override the non-leap month 7 Debug.Assert(calendarId == CalendarId.HEBREW && saMonthNames.Length == 13); saLeapYearMonthNames = (string[]) saMonthNames.Clone(); saLeapYearMonthNames[6] = leapHebrewMonthName; } result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames, ref leapHebrewMonthName); result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames); result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames); return result; } internal static int GetTwoDigitYearMax(CalendarId calendarId) { // There is no user override for this value on Linux or in ICU. // So just return -1 to use the hard-coded defaults. return -1; } // Call native side to figure out which calendars are allowed internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); // NOTE: there are no 'user overrides' on Linux int count = Interop.Globalization.GetCalendars(localeName, calendars, calendars.Length); // ensure there is at least 1 calendar returned if (count == 0 && calendars.Length > 0) { calendars[0] = CalendarId.GREGORIAN; count = 1; } return count; } private static bool SystemSupportsTaiwaneseCalendar() { return true; } // PAL Layer ends here private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.CallStringMethod( (locale, calId, type, stringBuilder) => Interop.Globalization.GetCalendarInfo( locale, calId, type, stringBuilder, stringBuilder.Capacity), localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns) { datePatterns = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); callbackContext.DisallowDuplicates = true; bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { List<string> datePatternsList = callbackContext.Results; datePatterns = new string[datePatternsList.Count]; for (int i = 0; i < datePatternsList.Count; i++) { datePatterns[i] = NormalizeDatePattern(datePatternsList[i]); } } return result; } /// <summary> /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. /// </summary> /// <remarks> /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// </remarks> private static string NormalizeDatePattern(string input) { StringBuilder destination = StringBuilderCache.Acquire(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': // single quotes escape characters, like 'de' in es-SP // so read verbatim until the next single quote destination.Append(input[index++]); while (index < input.Length) { char current = input[index++]; destination.Append(current); if (current == '\'') { break; } } break; case 'E': case 'e': case 'c': // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET // 'e' in ICU is the local day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET NormalizeDayOfWeek(input, destination, ref index); break; case 'L': case 'M': // 'L' in ICU is the stand-alone name of the month, // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns // 'M' in both ICU and .NET is the month, // but ICU supports 5 'M's, which is the super short month name int occurrences = CountOccurrences(input, input[index], ref index); if (occurrences > 4) { // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET occurrences = 3; } destination.Append('M', occurrences); break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET occurrences = CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning destination.Append('g'); break; case 'y': // a single 'y' in ICU is the year with no padding or trimming. // a single 'y' in .NET is the year with 1 or 2 digits // so convert any single 'y' to 'yyyy' occurrences = CountOccurrences(input, 'y', ref index); if (occurrences == 1) { occurrences = 4; } destination.Append('y', occurrences); break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, string.Format(CultureInfo.InvariantCulture, "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", input[index])); destination.Append(input[index++]); break; } } return StringBuilderCache.GetStringAndRelease(destination); } private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index) { char dayChar = input[index]; int occurrences = CountOccurrences(input, dayChar, ref index); occurrences = Math.Max(occurrences, 3); if (occurrences > 4) { // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET occurrences = 3; } destination.Append('d', occurrences); } private static int CountOccurrences(string input, char value, ref int index) { int startIndex = index; while (index < input.Length && input[index] == value) { index++; } return index - startIndex; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames, ref string leapHebrewMonthName) { monthNames = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an // extra empty string to fill the array. if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } if (callbackContext.Results.Count > 13) { Debug.Assert(calendarId == CalendarId.HEBREW && callbackContext.Results.Count == 14); if (calendarId == CalendarId.HEBREW) { leapHebrewMonthName = callbackContext.Results[13]; } callbackContext.Results.RemoveRange(13, callbackContext.Results.Count - 13); } monthNames = callbackContext.Results.ToArray(); } return result; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0) { string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] }; eraNames = latestEraName; } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData) { calendarData = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { calendarData = callbackContext.Results.ToArray(); } return result; } private static unsafe bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref EnumCalendarsData callbackContext) { return Interop.Globalization.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext)); } private static unsafe void EnumCalendarInfoCallback(string calendarString, IntPtr context) { try { ref EnumCalendarsData callbackContext = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)context); if (callbackContext.DisallowDuplicates) { foreach (string existingResult in callbackContext.Results) { if (string.Equals(calendarString, existingResult, StringComparison.Ordinal)) { // the value is already in the results, so don't add it again return; } } } callbackContext.Results.Add(calendarString); } catch (Exception e) { Debug.Fail(e.ToString()); // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code. // If we don't ignore the exception here that can cause the runtime to fail fast. } } private struct EnumCalendarsData { public List<string> Results; public bool DisallowDuplicates; } } }
// 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.Globalization; using System.Runtime.Serialization; using System.Configuration.Assemblies; using Internal.Reflection.Augments; namespace System.Reflection { public sealed class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { public AssemblyName() { HashAlgorithm = AssemblyHashAlgorithm.None; VersionCompatibility = AssemblyVersionCompatibility.SameMachine; _flags = AssemblyNameFlags.None; } public AssemblyName(string assemblyName) : this() { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); RuntimeAssemblyName runtimeAssemblyName = AssemblyNameParser.Parse(assemblyName); runtimeAssemblyName.CopyToAssemblyName(this); } public object Clone() { AssemblyName n = new AssemblyName(); n.Name = Name; n._publicKey = (byte[])_publicKey?.Clone(); n._publicKeyToken = (byte[])_publicKeyToken?.Clone(); n.CultureInfo = CultureInfo; n.Version = (Version)Version?.Clone(); n._flags = _flags; n.CodeBase = CodeBase; n.HashAlgorithm = HashAlgorithm; n.VersionCompatibility = VersionCompatibility; return n; } public ProcessorArchitecture ProcessorArchitecture { get { int x = (((int)_flags) & 0x70) >> 4; if (x > 5) x = 0; return (ProcessorArchitecture)x; } set { int x = ((int)value) & 0x07; if (x <= 5) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFFF0F); _flags |= (AssemblyNameFlags)(x << 4); } } } public AssemblyContentType ContentType { get { int x = (((int)_flags) & 0x00000E00) >> 9; if (x > 1) x = 0; return (AssemblyContentType)x; } set { int x = ((int)value) & 0x07; if (x <= 1) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFF1FF); _flags |= (AssemblyNameFlags)(x << 9); } } } public string CultureName { get { return CultureInfo?.Name; } set { CultureInfo = (value == null) ? null : new CultureInfo(value); } } public CultureInfo CultureInfo { get; set; } public AssemblyNameFlags Flags { get { return (AssemblyNameFlags)((uint)_flags & 0xFFFFF10F); } set { _flags &= unchecked((AssemblyNameFlags)0x00000EF0); _flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); } } public string FullName { get { if (this.Name == null) return string.Empty; // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. byte[] pkt = _publicKeyToken ?? AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); } } public string Name { get; set; } public Version Version { get; set; } public string CodeBase { get; set; } public AssemblyHashAlgorithm HashAlgorithm { get; set; } public AssemblyVersionCompatibility VersionCompatibility { get; set; } public StrongNameKeyPair KeyPair { get; set; } public string EscapedCodeBase { get { if (CodeBase == null) return null; else return EscapeCodeBase(CodeBase); } } public byte[] GetPublicKey() { return _publicKey; } public byte[] GetPublicKeyToken() { if (_publicKeyToken == null) _publicKeyToken = AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); return _publicKeyToken; } public void SetPublicKey(byte[] publicKey) { _publicKey = publicKey; if (publicKey == null) _flags &= ~AssemblyNameFlags.PublicKey; else _flags |= AssemblyNameFlags.PublicKey; } public void SetPublicKeyToken(byte[] publicKeyToken) { _publicKeyToken = publicKeyToken; } public override string ToString() { string s = FullName; if (s == null) return base.ToString(); else return s; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public void OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } public static AssemblyName GetAssemblyName(string assemblyFile) { throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported_AssemblyName_GetAssemblyName); } /// <summary> /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// </summary> public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) { if (object.ReferenceEquals(reference, definition)) return true; if (reference == null) throw new ArgumentNullException(nameof(reference)); if (definition == null) throw new ArgumentNullException(nameof(definition)); string refName = reference.Name ?? string.Empty; string defName = definition.Name ?? string.Empty; return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } internal static string EscapeCodeBase(string codebase) { throw new PlatformNotSupportedException(); } private AssemblyNameFlags _flags; private byte[] _publicKey; private byte[] _publicKeyToken; } }
// Storyboard.Designer.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### namespace Storyboards { partial class Storyboard { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Storyboard)); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.addItemToListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editCaptionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); // this.printSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); // this.exportSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.stretchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.addNewGroupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.imageListLarge = new System.Windows.Forms.ImageList(this.components); this.imageList = new System.Windows.Forms.ImageList(this.components); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.bPrevious = new System.Windows.Forms.ToolStripButton(); this.bNext = new System.Windows.Forms.ToolStripButton(); this.bDeleteItem = new System.Windows.Forms.ToolStripButton(); this.bTogglePictureBox = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bToggleView = new System.Windows.Forms.ToolStripButton(); this.viewLabel = new System.Windows.Forms.ToolStripLabel(); this.bRefresh = new System.Windows.Forms.ToolStripButton(); this.pictureBox = new System.Windows.Forms.PictureBox(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.textBoxPreview = new System.Windows.Forms.RichTextBox(); this.listView = new groupem_scrollmaster(); this.contextMenuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addItemToListToolStripMenuItem, this.editCaptionToolStripMenuItem, // this.printSelectedToolStripMenuItem, // this.exportSelectedToolStripMenuItem, this.deleteItemToolStripMenuItem, this.toolStripSeparator3, this.stretchToolStripMenuItem, this.toolStripSeparator2, this.addNewGroupToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(171, 170); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // addItemToListToolStripMenuItem // this.addItemToListToolStripMenuItem.Name = "addItemToListToolStripMenuItem"; this.addItemToListToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.addItemToListToolStripMenuItem.Text = "Add Item To List"; this.addItemToListToolStripMenuItem.Click += new System.EventHandler(this.addItemToListToolStripMenuItem_Click); // // editCaptionToolStripMenuItem // this.editCaptionToolStripMenuItem.Name = "editCaptionToolStripMenuItem"; this.editCaptionToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.editCaptionToolStripMenuItem.Text = "Edit Caption"; this.editCaptionToolStripMenuItem.ToolTipText = "Rename entries... this can be used to adjust their display order"; this.editCaptionToolStripMenuItem.Click += new System.EventHandler(this.editCaptionToolStripMenuItem_Click); // // printSelectedToolStripMenuItem // // this.printSelectedToolStripMenuItem.Name = "printSelectedToolStripMenuItem"; // this.printSelectedToolStripMenuItem.Size = new System.Drawing.Size(170, 22); // this.printSelectedToolStripMenuItem.Text = "Print Selected"; // this.printSelectedToolStripMenuItem.Click += new System.EventHandler(this.printSelectedToolStripMenuItem_Click); // // // // exportSelectedToolStripMenuItem // // // this.exportSelectedToolStripMenuItem.Name = "exportSelectedToolStripMenuItem"; // this.exportSelectedToolStripMenuItem.Size = new System.Drawing.Size(170, 22); // this.exportSelectedToolStripMenuItem.Text = "Export Selected"; // this.exportSelectedToolStripMenuItem.Click += new System.EventHandler(this.exportSelectedToolStripMenuItem_Click); // // deleteItemToolStripMenuItem // this.deleteItemToolStripMenuItem.Name = "deleteItemToolStripMenuItem"; this.deleteItemToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.deleteItemToolStripMenuItem.Text = "Delete Item"; this.deleteItemToolStripMenuItem.Click += new System.EventHandler(this.deleteItemToolStripMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(167, 6); // // stretchToolStripMenuItem // this.stretchToolStripMenuItem.Name = "stretchToolStripMenuItem"; this.stretchToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.stretchToolStripMenuItem.Text = "Toggle Image Size"; this.stretchToolStripMenuItem.Click += new System.EventHandler(this.stretchToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(167, 6); // // addNewGroupToolStripMenuItem // this.addNewGroupToolStripMenuItem.Name = "addNewGroupToolStripMenuItem"; this.addNewGroupToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.addNewGroupToolStripMenuItem.Text = "Add New Group..."; this.addNewGroupToolStripMenuItem.Click += new System.EventHandler(this.addNewGroupToolStripMenuItem_Click); // // imageListLarge FEB 2013 - As part of convesrion process I do not actually Think we need these default imagelists setup. // this.imageListLarge.Images.Add (CoreUtilities.FileUtils.GetImage_ForDLL ("photo.png")); this.imageListLarge.Images.SetKeyName(0, "photo.png"); // this.imageListLarge.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListLarge.ImageStream"))); // this.imageListLarge.TransparentColor = System.Drawing.Color.Transparent; // this.imageListLarge.Images.SetKeyName(0, "text_align_center.png"); // // // // imageList // // this.imageList.Images.Add(CoreUtilities.FileUtils.GetImage_ForDLL ("photo.png")); this.imageList.Images.SetKeyName(0,"photo.png"); // this.imageList.TransparentColor = System.Drawing.Color.Transparent; // this.imageList.Images.SetKeyName(0, "text_align_center.png"); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bPrevious, this.bNext, this.bDeleteItem, this.bTogglePictureBox, this.toolStripSeparator1, this.bToggleView, this.viewLabel, this.bRefresh}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(346, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // bPrevious // this.bPrevious.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bPrevious.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("arrow_left.png"); this.bPrevious.ImageTransparentColor = System.Drawing.Color.Magenta; this.bPrevious.Name = "bPrevious"; this.bPrevious.Size = new System.Drawing.Size(23, 22); this.bPrevious.ToolTipText = "Previous Image"; this.bPrevious.Click += new System.EventHandler(this.bPrevious_Click); // // bNext // this.bNext.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bNext.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("arrow_right.png"); this.bNext.ImageTransparentColor = System.Drawing.Color.Magenta; this.bNext.Name = "bNext"; this.bNext.Size = new System.Drawing.Size(23, 22); this.bNext.Text = "toolStripButton3"; this.bNext.ToolTipText = "Next Image"; this.bNext.Click += new System.EventHandler(this.bNext_Click); // // bDeleteItem // this.bDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bDeleteItem.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("delete.png"); this.bDeleteItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.bDeleteItem.Name = "bDeleteItem"; this.bDeleteItem.Size = new System.Drawing.Size(23, 22); this.bDeleteItem.Text = "toolStripButton1"; this.bDeleteItem.ToolTipText = "Delete Current Item... this will only remove the reference, not the actual file o" + "r linked item"; this.bDeleteItem.Click += new System.EventHandler(this.bDeleteItem_Click); // // bTogglePictureBox // this.bTogglePictureBox.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bTogglePictureBox.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("photo.png"); this.bTogglePictureBox.ImageTransparentColor = System.Drawing.Color.Magenta; this.bTogglePictureBox.Name = "bTogglePictureBox"; this.bTogglePictureBox.Size = new System.Drawing.Size(23, 22); this.bTogglePictureBox.Text = "toolStripButton2"; this.bTogglePictureBox.ToolTipText = "Toggle Preview"; this.bTogglePictureBox.Click += new System.EventHandler(this.bToggle_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // bToggleView // this.bToggleView.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bToggleView.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("picture_go.png"); this.bToggleView.ImageTransparentColor = System.Drawing.Color.Magenta; this.bToggleView.Name = "bToggleView"; this.bToggleView.Size = new System.Drawing.Size(23, 22); this.bToggleView.Text = "toolStripButton1"; this.bToggleView.ToolTipText = "Toggle View"; this.bToggleView.Click += new System.EventHandler(this.toolStripButton1_Click); // // viewLabel // this.viewLabel.Name = "viewLabel"; this.viewLabel.Size = new System.Drawing.Size(59, 22); this.viewLabel.Text = "SmallIcon"; // // bRefresh // this.bRefresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bRefresh.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("arrow_refresh.png"); this.bRefresh.ImageTransparentColor = System.Drawing.Color.Magenta; this.bRefresh.Name = "bRefresh"; this.bRefresh.Size = new System.Drawing.Size(23, 22); this.bRefresh.Text = "Refresh"; this.bRefresh.ToolTipText = "If entries are missing press this to refresh the display"; this.bRefresh.Click += new System.EventHandler(this.bRefresh_Click); // // pictureBox // this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Location = new System.Drawing.Point(0, 0); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(150, 46); this.pictureBox.TabIndex = 2; this.pictureBox.TabStop = false; this.pictureBox.Visible = false; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 25); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.listView); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.textBoxPreview); this.splitContainer1.Panel2.Controls.Add(this.pictureBox); this.splitContainer1.Panel2Collapsed = true; this.splitContainer1.Size = new System.Drawing.Size(346, 373); this.splitContainer1.SplitterDistance = 186; this.splitContainer1.TabIndex = 3; // // textBoxPreview // this.textBoxPreview.Location = new System.Drawing.Point(56, 50); this.textBoxPreview.Name = "textBoxPreview"; this.textBoxPreview.ReadOnly = true; this.textBoxPreview.Size = new System.Drawing.Size(100, 96); this.textBoxPreview.TabIndex = 3; this.textBoxPreview.Text = ""; // // listView // this.listView.AllowDrop = false; this.listView.ContextMenuStrip = this.contextMenuStrip1; this.listView.Dock = System.Windows.Forms.DockStyle.Fill; this.listView.FullRowSelect = true; this.listView.HideSelection = false; this.listView.LargeImageList = this.imageListLarge; this.listView.Location = new System.Drawing.Point(0, 0); this.listView.Name = "listView"; this.listView.ScrollPosition = 0; this.listView.Size = new System.Drawing.Size(346, 373); this.listView.SmallImageList = this.imageList; this.listView.TabIndex = 0; this.listView.TileSize = new System.Drawing.Size(48, 48); this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.SmallIcon; this.listView.SelectedIndexChanged += new System.EventHandler(this.listView_SelectedIndexChanged); this.listView.DoubleClick += new System.EventHandler(this.listView_DoubleClick); this.listView.Leave += new System.EventHandler(this.listView_Leave); this.listView.Enter += new System.EventHandler(this.listView_Enter); this.listView.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView_DragDrop); this.listView.MouseEnter += new System.EventHandler(this.listView_MouseEnter); this.listView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView_ColumnClick); this.listView.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView_DragEnter); this.listView.onScroll += new System.Windows.Forms.ScrollEventHandler(this.listView_onScroll); // this.listView.Click += new System.EventHandler(this.listView_Click); // // groupEms // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Controls.Add(this.splitContainer1); this.Controls.Add(this.toolStrip1); this.Name = "groupEms"; this.Size = new System.Drawing.Size(346, 398); this.Load += new System.EventHandler(this.groupEms_Load); this.Enter += new System.EventHandler(this.groupEms_Enter); this.MouseEnter += new System.EventHandler(this.groupEms_MouseEnter); this.contextMenuStrip1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton bToggleView; private System.Windows.Forms.ImageList imageListLarge; private System.Windows.Forms.ToolStripLabel viewLabel; private System.Windows.Forms.ToolStripButton bPrevious; private System.Windows.Forms.ToolStripButton bNext; private System.Windows.Forms.ToolStripButton bTogglePictureBox; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem addNewGroupToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem editCaptionToolStripMenuItem; private System.Windows.Forms.ToolStripButton bDeleteItem; // private System.Windows.Forms.ToolStripMenuItem printSelectedToolStripMenuItem; // private System.Windows.Forms.ToolStripMenuItem exportSelectedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addItemToListToolStripMenuItem; private System.Windows.Forms.ToolStripButton bRefresh; private System.Windows.Forms.ToolStripMenuItem deleteItemToolStripMenuItem; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.RichTextBox textBoxPreview; private System.Windows.Forms.ToolStripMenuItem stretchToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; public groupem_scrollmaster listView; } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Net; using System.Net.Sockets; using gov.va.medora.utils; using gov.va.medora.mdo.exceptions; using gov.va.medora.mdo.src.mdo; using System.IO; namespace gov.va.medora.mdo.dao.vista { public class VistaConnection : AbstractConnection { public Dictionary<string, bool> IssedBulletin = new Dictionary<string, bool>(); public IList<string> Rpcs = new List<string>(); const int CONNECTION_TIMEOUT = 30000; const int READ_TIMEOUT = 120000; const int DEFAULT_PORT = 9200; public Socket socket; public int port; ISystemFileHandler sysFileHandler; public VistaConnection(DataSource dataSource) : base(dataSource) { Account = new VistaAccount(this); if (ConnectTimeout == 0) { ConnectTimeout = CONNECTION_TIMEOUT; } if (ReadTimeout == 0) { ReadTimeout = READ_TIMEOUT; } port = (dataSource.Port == 0) ? DEFAULT_PORT : dataSource.Port; sysFileHandler = new VistaSystemFileHandler(this); } public override void connect() { IsConnecting = true; ConnectStrategy.connect(); IsTestSource = isTestSystem(); IsConnecting = false; } // Needs to return object so it can be either User or Exception on multi-site connections. public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource) { try { connect(); return Account.authenticateAndAuthorize(credentials, permission, validationDataSource); } catch (Exception ex) { return ex; } } public override ISystemFileHandler SystemFileHandler { get { if (sysFileHandler == null) { sysFileHandler = new VistaSystemFileHandler(this); } return sysFileHandler; } } public override object query(MdoQuery vq, AbstractPermission context = null) { // see http://trac.medora.va.gov/web/ticket/2716 //if (Rpcs == null) //{ // Rpcs = new List<string>(); //} //Rpcs.Add(vq.RpcName); //if (String.Equals(vq.RpcName, "DDR LISTER")) //{ // return query(vq, context, true); //} string request = vq.buildMessage(); return query(request, context); } //public VistaRpcQuery query(MdoQuery request, AbstractPermission context, bool vistaRpcQuery) //{ // if (!vistaRpcQuery) // { // throw new NotImplementedException("Only used for DDR RPCs"); // } // VistaRpcQuery result = new VistaRpcQuery(); // result.RequestString = request.buildMessage(); // result.RequestTime = DateTime.Now; // result.ResponseString = (String)query(result.RequestString, context); // result.ResponseTime = DateTime.Now; // return result; //} public override object query(string request, AbstractPermission context = null) { // see http://trac.medora.va.gov/web/ticket/2716 //if (Rpcs == null) //{ // Rpcs = new List<string>(); //} //try //{ // // TBD - do we want to just not log calls if not passed through query(MdoQuery)??? it seems excessive to use reflection on every query // // to determine if the calling function was query(MdoQuery) and thus has already been logged. // // don't want to duplicate calls being logged by query(MdoQuery) so make sure that was NOT the calling function // if (!String.Equals(new System.Diagnostics.StackFrame(1).GetMethod().Name, "query", StringComparison.CurrentCultureIgnoreCase)) // { // // we can't get RPC since we just received message but that information is human readable so save anyways // Rpcs.Add(request); // } //} //catch (Exception) { /* don't want to blow everything up - just hide this */ } if (!IsConnecting && !IsConnected) { throw new NotConnectedException(); } AbstractPermission currentContext = null; if (context != null && context.Name != this.Account.PrimaryPermission.Name) { currentContext = this.Account.PrimaryPermission; ((VistaAccount)this.Account).setContext(context); } Byte[] bytesSent = Encoding.ASCII.GetBytes(request); Byte[] bytesReceived = new Byte[256]; socket.Send(bytesSent, bytesSent.Length, 0); int bytes = 0; string reply = ""; StringBuilder sb = new StringBuilder(); string thisBatch = ""; //bool isHdr = true; bool isErrorMsg = false; int endIdx = -1; // first read from socket so we don't need to use isHdr any more bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); if (bytes == 0) { throw new ConnectionException("Timeout waiting for response from VistA"); } thisBatch = Encoding.ASCII.GetString(bytesReceived, 0, bytes); endIdx = thisBatch.IndexOf('\x04'); if (endIdx != -1) { thisBatch = thisBatch.Substring(0, endIdx); } if (bytesReceived[0] != 0) { thisBatch = thisBatch.Substring(1, bytesReceived[0]); isErrorMsg = true; } else if (bytesReceived[1] != 0) { thisBatch = thisBatch.Substring(2); isErrorMsg = true; } else { thisBatch = thisBatch.Substring(2); } sb.Append(thisBatch); // now we can start reading from socket in a loop MemoryStream ms = new MemoryStream(); while (endIdx == -1) { bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); if (bytes == 0) { throw new ConnectionException("Timeout waiting for response from VistA"); } for (int i = 0; i < bytes; i++) { if (bytesReceived[i] == '\x04') { endIdx = i; break; } else { ms.WriteByte(bytesReceived[i]); } } } sb.Append(Encoding.ASCII.GetString(ms.ToArray())); reply = sb.ToString(); if (currentContext != null) { ((VistaAccount)this.Account).setContext(currentContext); } if (isErrorMsg || reply.Contains("M ERROR")) { throw new MdoException(MdoExceptionCode.VISTA_FAULT, reply); } //return StringUtils.stripInvalidXmlCharacters(reply); // start cleaning all Vista responses - too tedious to do on a case by case basis return reply; } public override void disconnect() { //if (!IsConnected) //{ // return; //} try { string msg = "[XWB]10304\x0005#BYE#\x0004"; msg = (string)query(msg); socket.Disconnect(false); socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); // System.Console.WriteLine("Successful disconnect!"); } catch (Exception) { // System.Console.WriteLine("Exception on disconnect: " + exc.Message); } finally { IsConnected = false; // must be down here because query depends on IsConnected = true } } public override string getWelcomeMessage() { MdoQuery request = buildGetWelcomeMessageRequest(); string response = (string)query(request); return response; } internal MdoQuery buildGetWelcomeMessageRequest() { return new VistaQuery("XUS INTRO MSG"); } public override bool hasPatch(string patchId) { MdoQuery request = buildHasPatchRequest(patchId); string response = (string)query(request); return (response == "1"); } internal MdoQuery buildHasPatchRequest(string patchId) { VistaQuery vq = new VistaQuery("ORWU PATCH"); vq.addParameter(vq.LITERAL, patchId); return vq; } internal bool isTestSystem() { VistaQuery vq = new VistaQuery("XUS SIGNON SETUP"); string response = (string)query(vq.buildMessage()); string[] flds = StringUtils.split(response, StringUtils.CRLF); return flds[7] == "0"; } public override string getServerTimeout() { string arg = "$P($G(^XTV(8989.3,1,\"XWB\")),U)"; MdoQuery request = VistaUtils.buildGetVariableValueRequest(arg); string response = (string)query(request); return response; } public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null) { throw new NotImplementedException(); } #region Symbol Table /// <summary> /// Set the connections session variable to the symbol table /// </summary> public void setSymbolTable() { setState(this.Session); } public override void setState(Dictionary<string, object> sessionTable) { MdoQuery request = buildSetSymbolTableRequest(sessionTable); string response = (string)query(request.buildMessage()); if (!String.Equals(response, "1")) { throw new MdoException("Unable to deserialize symbol table! Vista code: {0}", response); } } internal MdoQuery buildSetSymbolTableRequest(Dictionary<string, object> sessionTable) { VistaQuery request = new VistaQuery("XWB DESERIALIZE"); DictionaryHashList dhl = new DictionaryHashList(); string[] allKeys = new string[sessionTable.Count]; sessionTable.Keys.CopyTo(allKeys, 0); for (int i = 0; i < sessionTable.Count; i++) { dhl.Add((i + 1).ToString(), (object)String.Concat(allKeys[i], '\x1e', sessionTable[allKeys[i]])); } request.addParameter(request.LIST, dhl); return request; } public override Dictionary<string, object> getState() { return getSerializedSymbolTable(); } internal Dictionary<string, object> getSerializedSymbolTable() { MdoQuery request = buildGetSerializedSymbolTableRequest(); string response = (string)query(request); return toSerializedSymbolTable(response); } internal MdoQuery buildGetSerializedSymbolTableRequest() { MdoQuery request = new VistaQuery("XWB SERIALIZE"); return request; } internal Dictionary<string, object> toSerializedSymbolTable(string response) { Dictionary<string, object> result = new Dictionary<string, object>(); string[] lines = StringUtils.split(response, '\x1f'); foreach (string line in lines) { if (String.IsNullOrEmpty(line)) { continue; } string[] pieces = StringUtils.split(line, '\x1e'); string key = pieces[0]; object value = null; if (String.IsNullOrEmpty(pieces[1]) || pieces[1].StartsWith("\"")) { value = pieces[1] as string; } else { value = pieces[1]; } result.Add(key, value); } return result; } #endregion public void heartbeat() { VistaQuery vq = new VistaQuery("XWB IM HERE"); this.query(vq); } } }
using System; using System.IO; using System.Net; using System.Text; using Box.V2.Utility; using Newtonsoft.Json.Linq; namespace Box.V2.Config { public sealed class BoxConfig : IBoxConfig { internal static string DefaultUserAgent = "Box Windows SDK v" + AssemblyInfo.NuGetVersion; /// <summary> /// Instantiates a Box config with all of the standard defaults /// </summary> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="redirectUri"></param> public BoxConfig(string clientId, string clientSecret, Uri redirectUri) { ClientId = clientId; ClientSecret = clientSecret; RedirectUri = redirectUri; UserAgent = DefaultUserAgent; } /// <summary> /// Instantiates a Box config for use with JWT authentication /// </summary> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="enterpriseId"></param> /// <param name="jwtPrivateKey"></param> /// <param name="jwtPrivateKeyPassword"></param> /// <param name="jwtPublicKeyId"></param> public BoxConfig(string clientId, string clientSecret, string enterpriseId, string jwtPrivateKey, string jwtPrivateKeyPassword, string jwtPublicKeyId) { ClientId = clientId; ClientSecret = clientSecret; EnterpriseId = enterpriseId; JWTPrivateKey = jwtPrivateKey; JWTPrivateKeyPassword = jwtPrivateKeyPassword; JWTPublicKeyId = jwtPublicKeyId; UserAgent = DefaultUserAgent; } public BoxConfig(BoxConfigBuilder builder) { ClientId = builder.ClientId; ClientSecret = builder.ClientSecret; EnterpriseId = builder.EnterpriseId; JWTPrivateKey = builder.JWTPrivateKey; JWTPrivateKeyPassword = builder.JWTPrivateKeyPassword; JWTPublicKeyId = builder.JWTPublicKeyId; UserAgent = builder.UserAgent; BoxApiHostUri = builder.BoxApiHostUri; BoxAccountApiHostUri = builder.BoxAccountApiHostUri; BoxApiUri = builder.BoxApiUri; BoxUploadApiUri = builder.BoxUploadApiUri; BoxAuthTokenApiUri = builder.BoxAuthTokenApiUri; RedirectUri = builder.RedirectUri; DeviceId = builder.DeviceId; DeviceName = builder.DeviceName; AcceptEncoding = builder.AcceptEncoding; WebProxy = builder.WebProxy; Timeout = builder.Timeout; } /// <summary> /// Create BoxConfig from json file. /// </summary> /// <param name="jsonFile">json file stream.</param> /// <returns>IBoxConfig instance.</returns> public static IBoxConfig CreateFromJsonFile(Stream jsonFile) { var jsonString = string.Empty; using (var reader = new StreamReader(jsonFile, Encoding.UTF8)) { jsonString = reader.ReadToEnd(); } return CreateFromJsonString(jsonString); } /// <summary> /// Create BoxConfig from json string /// </summary> /// <param name="jsonString">json string.</param> /// <returns>IBoxConfig instance.</returns> public static IBoxConfig CreateFromJsonString(string jsonString) { var json = JObject.Parse(jsonString); string clientId = null; string clientSecret = null; string enterpriseId = null; string privateKey = null; string rsaSecret = null; string publicKeyId = null; if (json["boxAppSettings"] != null) { var boxAppSettings = json["boxAppSettings"]; if (boxAppSettings["clientID"] != null) { clientId = boxAppSettings["clientID"].ToString(); } if (boxAppSettings["clientSecret"] != null) { clientSecret = boxAppSettings["clientSecret"].ToString(); } if (boxAppSettings["appAuth"] != null) { var appAuth = boxAppSettings["appAuth"]; if (appAuth["privateKey"] != null) { privateKey = appAuth["privateKey"].ToString(); } if (appAuth["passphrase"] != null) { rsaSecret = appAuth["passphrase"].ToString(); } if (appAuth["publicKeyID"] != null) { publicKeyId = appAuth["publicKeyID"].ToString(); } } } if (json["enterpriseID"] != null) { enterpriseId = json["enterpriseID"].ToString(); } return new BoxConfig(clientId, clientSecret, enterpriseId, privateKey, rsaSecret, publicKeyId); } public Uri BoxApiHostUri { get; private set; } = new Uri(Constants.BoxApiHostUriString); public Uri BoxAccountApiHostUri { get; private set; } = new Uri(Constants.BoxAccountApiHostUriString); public Uri BoxApiUri { get; private set; } = new Uri(Constants.BoxApiUriString); public Uri BoxUploadApiUri { get; private set; } = new Uri(Constants.BoxUploadApiUriString); public Uri BoxAuthTokenApiUri { get; private set; } = new Uri(Constants.BoxAuthTokenApiUriString); public string ClientId { get; private set; } public string ConsumerKey { get; private set; } public string ClientSecret { get; private set; } public Uri RedirectUri { get; private set; } public string EnterpriseId { get; private set; } public string JWTPrivateKey { get; private set; } public string JWTPrivateKeyPassword { get; private set; } public string JWTPublicKeyId { get; private set; } public string DeviceId { get; private set; } public string DeviceName { get; private set; } public string UserAgent { get; private set; } /// <summary> /// Sends compressed responses from Box for faster response times /// </summary> public CompressionType? AcceptEncoding { get; private set; } public Uri AuthCodeBaseUri { get { return new Uri(BoxAccountApiHostUri, Constants.AuthCodeString); } } public Uri AuthCodeUri { get { return new Uri(AuthCodeBaseUri, string.Format("?response_type=code&client_id={0}&redirect_uri={1}", ClientId, RedirectUri)); } } public Uri FoldersEndpointUri { get { return new Uri(BoxApiUri, Constants.FoldersString); } } public Uri TermsOfServicesUri { get { return new Uri(BoxApiUri, Constants.TermsOfServicesString); } } public Uri TermsOfServiceUserStatusesUri { get { return new Uri(BoxApiUri, Constants.TermsOfServiceUserStatusesString); } } public Uri FilesEndpointUri { get { return new Uri(BoxApiUri, Constants.FilesString); } } public Uri FilesUploadEndpointUri { get { return new Uri(BoxUploadApiUri, Constants.FilesUploadString); } } /// <summary> /// Upload session /// </summary> public Uri FilesUploadSessionEndpointUri { get { return new Uri(BoxUploadApiUri, Constants.FilesUploadSessionString); } } public Uri FilesPreflightCheckUri { get { return new Uri(BoxApiUri, Constants.FilesUploadString); } } public Uri CommentsEndpointUri { get { return new Uri(BoxApiUri, Constants.CommentsString); } } public Uri SearchEndpointUri { get { return new Uri(BoxApiUri, Constants.SearchString); } } public Uri UserEndpointUri { get { return new Uri(BoxApiUri, Constants.UserString); } } public Uri InviteEndpointUri { get { return new Uri(BoxApiUri, Constants.InviteString); } } public Uri CollaborationsEndpointUri { get { return new Uri(BoxApiUri, Constants.CollaborationsString); } } public Uri GroupsEndpointUri { get { return new Uri(BoxApiUri, Constants.GroupsString); } } public Uri GroupMembershipEndpointUri { get { return new Uri(BoxApiUri, Constants.GroupMembershipString); } } public Uri RetentionPoliciesEndpointUri { get { return new Uri(BoxApiUri, Constants.RetentionPoliciesString); } } public Uri RetentionPolicyAssignmentsUri { get { return new Uri(BoxApiUri, Constants.RetentionPolicyAssignmentsString); } } public Uri FileVersionRetentionsUri { get { return new Uri(BoxApiUri, Constants.FileVersionRetentionsString); } } public Uri EventsUri { get { return new Uri(BoxApiUri, Constants.EventsString); } } public Uri MetadataTemplatesUri { get { return new Uri(BoxApiUri, Constants.MetadataTemplatesString); } } public Uri CreateMetadataTemplateUri { get { return new Uri(BoxApiUri, Constants.CreateMetadataTemplateString); } } public Uri MetadataQueryUri { get { return new Uri(BoxApiUri, Constants.MetadataQueryString); } } public Uri WebhooksUri { get { return new Uri(BoxApiUri, Constants.WebhooksString); } } public Uri RecentItemsUri { get { return new Uri(BoxApiUri, Constants.RecentItemsString); } } public Uri EnterprisesUri { get { return new Uri(BoxApiUri, Constants.EnterprisesString); } } public Uri DevicePinUri { get { return new Uri(BoxApiUri, Constants.DevicePinString); } } public Uri CollaborationWhitelistEntryUri { get { return new Uri(BoxApiUri, Constants.CollaborationWhitelistEntryString); } } public Uri CollaborationWhitelistTargetEntryUri { get { return new Uri(BoxApiUri, Constants.CollaborationWhitelistTargetEntryString); } } public Uri MetadataCascadePolicyUri { get { return new Uri(BoxApiUri, Constants.MetadataCascadePoliciesString); } } public Uri StoragePoliciesUri { get { return new Uri(BoxApiUri, Constants.StoragePoliciesString); } } public Uri StoragePolicyAssignmentsUri { get { return new Uri(BoxApiUri, Constants.StoragePolicyAssignmentsString); } } public Uri StoragePolicyAssignmentsForTargetUri { get { return new Uri(BoxApiUri, Constants.StoragePolicyAssignmentsForTargetString); } } /// <summary> /// Gets the shared items endpoint URI. /// </summary> /// <value> /// The shared items endpoint URI. /// </value> public Uri SharedItemsUri { get { return new Uri(BoxApiUri, Constants.SharedItemsString); } } /// <summary> /// Gets the task assignments endpoint URI. /// </summary> /// <value> /// The task assignments endpoint URI. /// </value> public Uri TaskAssignmentsEndpointUri { get { return new Uri(BoxApiUri, Constants.TaskAssignmentsString); } } /// <summary> /// Gets the tasks endpoint URI. /// </summary> public Uri TasksEndpointUri { get { return new Uri(BoxApiUri, Constants.TasksString); } } /// <summary> /// Gets the collections endpoint URI. /// </summary> /// <value> /// The collections endpoint URI. /// </value> public Uri CollectionsEndpointUri { get { return new Uri(BoxApiUri, Constants.CollectionsString); } } /// <summary> /// Gets the web links endpoint URI. /// </summary> public Uri WebLinksEndpointUri { get { return new Uri(BoxApiUri, Constants.WebLinksString); } } /// <summary> /// Gets the legal hold policies endpoint URI. /// </summary> public Uri LegalHoldPoliciesEndpointUri { get { return new Uri(BoxApiUri, Constants.LegalHoldPoliciesString); } } /// <summary> /// Gets the legal hold policies endpoint URI. /// </summary> public Uri LegalHoldPolicyAssignmentsEndpointUri { get { return new Uri(BoxApiUri, Constants.LegalHoldPolicyAssignmentsString); } } /// <summary> /// Gets the file viersion legal holds endpoint URI. /// </summary> public Uri FileVersionLegalHoldsEndpointUri { get { return new Uri(BoxApiUri, Constants.FileVersionLegalHoldsString); } } /// <summary> /// Gets the zip downloads endpoint URI. /// </summary> public Uri ZipDownloadsEndpointUri { get { return new Uri(BoxApiUri, Constants.ZipDownloadsString); } } /// <summary> /// Gets the folder locks endpoint URI. /// </summary> public Uri FolderLocksEndpointUri { get { return new Uri(BoxApiUri, Constants.FolderLocksString); } } /// <summary> /// Gets the sign requests endpoint URI. /// </summary> public Uri SignRequestsEndpointUri { get { return new Uri(BoxApiUri, Constants.SignRequestsString); } } /// <summary> /// Gets the sign requests endpoint URI. /// </summary> public Uri SignRequestsEndpointWithPathUri { get { return new Uri(BoxApiUri, Constants.SignRequestsWithPathString); } } /// <summary> /// Gets the file requests endpoint URI. /// </summary> public Uri FileRequestsEndpointWithPathUri { get { return new Uri(BoxApiUri, Constants.FileRequestsWithPathString); } } /// <summary> /// The web proxy for HttpRequestHandler /// </summary> public IWebProxy WebProxy { get; private set; } /// <summary> /// Timeout for the connection /// </summary> public TimeSpan? Timeout { get; private set; } } public enum CompressionType { gzip, deflate } }
namespace Humidifier.CodeBuild { using System.Collections.Generic; using ProjectTypes; public class Project : Humidifier.Resource { public static class Attributes { public static string Arn = "Arn" ; } public override string AWSTypeName { get { return @"AWS::CodeBuild::Project"; } } /// <summary> /// Description /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-description /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Description { get; set; } /// <summary> /// VpcConfig /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-vpcconfig /// Required: False /// UpdateType: Mutable /// Type: VpcConfig /// </summary> public VpcConfig VpcConfig { get; set; } /// <summary> /// SecondarySources /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-secondarysources /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Source /// </summary> public List<Source> SecondarySources { get; set; } /// <summary> /// EncryptionKey /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-encryptionkey /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic EncryptionKey { get; set; } /// <summary> /// SourceVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-sourceversion /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SourceVersion { get; set; } /// <summary> /// Triggers /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-triggers /// Required: False /// UpdateType: Mutable /// Type: ProjectTriggers /// </summary> public ProjectTriggers Triggers { get; set; } /// <summary> /// SecondaryArtifacts /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-secondaryartifacts /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Artifacts /// </summary> public List<Artifacts> SecondaryArtifacts { get; set; } /// <summary> /// Source /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-source /// Required: True /// UpdateType: Mutable /// Type: Source /// </summary> public Source Source { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-name /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// Artifacts /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-artifacts /// Required: True /// UpdateType: Mutable /// Type: Artifacts /// </summary> public Artifacts Artifacts { get; set; } /// <summary> /// BadgeEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-badgeenabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic BadgeEnabled { get; set; } /// <summary> /// LogsConfig /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-logsconfig /// Required: False /// UpdateType: Mutable /// Type: LogsConfig /// </summary> public LogsConfig LogsConfig { get; set; } /// <summary> /// ServiceRole /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-servicerole /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ServiceRole { get; set; } /// <summary> /// QueuedTimeoutInMinutes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-queuedtimeoutinminutes /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic QueuedTimeoutInMinutes { get; set; } /// <summary> /// FileSystemLocations /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-filesystemlocations /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: ProjectFileSystemLocation /// </summary> public List<ProjectFileSystemLocation> FileSystemLocations { get; set; } /// <summary> /// Environment /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-environment /// Required: True /// UpdateType: Mutable /// Type: Environment /// </summary> public Environment Environment { get; set; } /// <summary> /// SecondarySourceVersions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-secondarysourceversions /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: ProjectSourceVersion /// </summary> public List<ProjectSourceVersion> SecondarySourceVersions { get; set; } /// <summary> /// Tags /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-tags /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Tag /// </summary> public List<Tag> Tags { get; set; } /// <summary> /// TimeoutInMinutes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-timeoutinminutes /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic TimeoutInMinutes { get; set; } /// <summary> /// Cache /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-cache /// Required: False /// UpdateType: Mutable /// Type: ProjectCache /// </summary> public ProjectCache Cache { get; set; } } namespace ProjectTypes { public class ProjectSourceVersion { /// <summary> /// SourceIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectsourceversion.html#cfn-codebuild-project-projectsourceversion-sourceidentifier /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SourceIdentifier { get; set; } /// <summary> /// SourceVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectsourceversion.html#cfn-codebuild-project-projectsourceversion-sourceversion /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SourceVersion { get; set; } } public class LogsConfig { /// <summary> /// CloudWatchLogs /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-logsconfig.html#cfn-codebuild-project-logsconfig-cloudwatchlogs /// Required: False /// UpdateType: Mutable /// Type: CloudWatchLogsConfig /// </summary> public CloudWatchLogsConfig CloudWatchLogs { get; set; } /// <summary> /// S3Logs /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-logsconfig.html#cfn-codebuild-project-logsconfig-s3logs /// Required: False /// UpdateType: Mutable /// Type: S3LogsConfig /// </summary> public S3LogsConfig S3Logs { get; set; } } public class SourceAuth { /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// Resource /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-resource /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Resource { get; set; } } public class Environment { /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// EnvironmentVariables /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-environmentvariables /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: EnvironmentVariable /// </summary> public List<EnvironmentVariable> EnvironmentVariables { get; set; } /// <summary> /// PrivilegedMode /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-privilegedmode /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic PrivilegedMode { get; set; } /// <summary> /// ImagePullCredentialsType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-imagepullcredentialstype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ImagePullCredentialsType { get; set; } /// <summary> /// Image /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-image /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Image { get; set; } /// <summary> /// RegistryCredential /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-registrycredential /// Required: False /// UpdateType: Mutable /// Type: RegistryCredential /// </summary> public RegistryCredential RegistryCredential { get; set; } /// <summary> /// ComputeType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-computetype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ComputeType { get; set; } /// <summary> /// Certificate /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-certificate /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Certificate { get; set; } } public class GitSubmodulesConfig { /// <summary> /// FetchSubmodules /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-gitsubmodulesconfig.html#cfn-codebuild-project-gitsubmodulesconfig-fetchsubmodules /// Required: True /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic FetchSubmodules { get; set; } } public class VpcConfig { /// <summary> /// Subnets /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-subnets /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic Subnets { get; set; } /// <summary> /// VpcId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-vpcid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic VpcId { get; set; } /// <summary> /// SecurityGroupIds /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-securitygroupids /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic SecurityGroupIds { get; set; } } public class ProjectFileSystemLocation { /// <summary> /// MountPoint /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectfilesystemlocation.html#cfn-codebuild-project-projectfilesystemlocation-mountpoint /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic MountPoint { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectfilesystemlocation.html#cfn-codebuild-project-projectfilesystemlocation-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// Identifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectfilesystemlocation.html#cfn-codebuild-project-projectfilesystemlocation-identifier /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Identifier { get; set; } /// <summary> /// MountOptions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectfilesystemlocation.html#cfn-codebuild-project-projectfilesystemlocation-mountoptions /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic MountOptions { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectfilesystemlocation.html#cfn-codebuild-project-projectfilesystemlocation-location /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } } public class S3LogsConfig { /// <summary> /// Status /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-s3logsconfig.html#cfn-codebuild-project-s3logsconfig-status /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Status { get; set; } /// <summary> /// EncryptionDisabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-s3logsconfig.html#cfn-codebuild-project-s3logsconfig-encryptiondisabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic EncryptionDisabled { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-s3logsconfig.html#cfn-codebuild-project-s3logsconfig-location /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } } public class WebhookFilter { /// <summary> /// Pattern /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-webhookfilter.html#cfn-codebuild-project-webhookfilter-pattern /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Pattern { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-webhookfilter.html#cfn-codebuild-project-webhookfilter-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// ExcludeMatchedPattern /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-webhookfilter.html#cfn-codebuild-project-webhookfilter-excludematchedpattern /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic ExcludeMatchedPattern { get; set; } } public class Artifacts { /// <summary> /// Path /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-path /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Path { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// ArtifactIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-artifactidentifier /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ArtifactIdentifier { get; set; } /// <summary> /// OverrideArtifactName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-overrideartifactname /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic OverrideArtifactName { get; set; } /// <summary> /// Packaging /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-packaging /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Packaging { get; set; } /// <summary> /// EncryptionDisabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-encryptiondisabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic EncryptionDisabled { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-location /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-name /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// NamespaceType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-namespacetype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NamespaceType { get; set; } } public class RegistryCredential { /// <summary> /// Credential /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-registrycredential.html#cfn-codebuild-project-registrycredential-credential /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Credential { get; set; } /// <summary> /// CredentialProvider /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-registrycredential.html#cfn-codebuild-project-registrycredential-credentialprovider /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic CredentialProvider { get; set; } } public class CloudWatchLogsConfig { /// <summary> /// Status /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-cloudwatchlogsconfig.html#cfn-codebuild-project-cloudwatchlogsconfig-status /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Status { get; set; } /// <summary> /// GroupName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-cloudwatchlogsconfig.html#cfn-codebuild-project-cloudwatchlogsconfig-groupname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic GroupName { get; set; } /// <summary> /// StreamName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-cloudwatchlogsconfig.html#cfn-codebuild-project-cloudwatchlogsconfig-streamname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic StreamName { get; set; } } public class ProjectCache { /// <summary> /// Modes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectcache.html#cfn-codebuild-project-projectcache-modes /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic Modes { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectcache.html#cfn-codebuild-project-projectcache-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projectcache.html#cfn-codebuild-project-projectcache-location /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } } public class FilterGroup { } public class ProjectTriggers { /// <summary> /// FilterGroups /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projecttriggers.html#cfn-codebuild-project-projecttriggers-filtergroups /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: FilterGroup /// </summary> public List<FilterGroup> FilterGroups { get; set; } /// <summary> /// Webhook /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-projecttriggers.html#cfn-codebuild-project-projecttriggers-webhook /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic Webhook { get; set; } } public class EnvironmentVariable { /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-type /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// Value /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-value /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Value { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class Source { /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } /// <summary> /// ReportBuildStatus /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-reportbuildstatus /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic ReportBuildStatus { get; set; } /// <summary> /// Auth /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-auth /// Required: False /// UpdateType: Mutable /// Type: SourceAuth /// </summary> public SourceAuth Auth { get; set; } /// <summary> /// SourceIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-sourceidentifier /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SourceIdentifier { get; set; } /// <summary> /// BuildSpec /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-buildspec /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic BuildSpec { get; set; } /// <summary> /// GitCloneDepth /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-gitclonedepth /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic GitCloneDepth { get; set; } /// <summary> /// GitSubmodulesConfig /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-gitsubmodulesconfig /// Required: False /// UpdateType: Mutable /// Type: GitSubmodulesConfig /// </summary> public GitSubmodulesConfig GitSubmodulesConfig { get; set; } /// <summary> /// InsecureSsl /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-insecuressl /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic InsecureSsl { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-location /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } } } }
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 RestfullService.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; } } }
using Neo.Compiler.MSIL.Utils; using Neo.IO.Json; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; using Neo.VM; using Neo.VM.Types; using System; using System.Collections.Generic; using System.IO; namespace Neo.Compiler.MSIL.UnitTests.Utils { public class TestEngine : ApplicationEngine { public const long TestGas = 2000_000_000; public static InteropDescriptor Native_Deploy; static TestEngine() { // Extract Native deploy syscall Native_Deploy = Neo_Native_Deploy; } static readonly IDictionary<string, BuildScript> scriptsAll = new Dictionary<string, BuildScript>(); public readonly IDictionary<string, BuildScript> Scripts; public BuildScript ScriptEntry { get; private set; } public TestEngine(TriggerType trigger = TriggerType.Application, IVerifiable verificable = null, StoreView snapshot = null) : base(trigger, verificable, snapshot ?? new TestSnapshot(), TestGas) { Scripts = new Dictionary<string, BuildScript>(); } public BuildScript Build(string filename, bool releaseMode = false, bool optimizer = true) { var contains = scriptsAll.ContainsKey(filename); if (!contains || (contains && scriptsAll[filename].UseOptimizer != optimizer)) { if (Path.GetExtension(filename).ToLowerInvariant() == ".nef") { var fileNameManifest = filename; using (BinaryReader reader = new BinaryReader(File.OpenRead(filename))) { NefFile neffile = new NefFile(); neffile.Deserialize(reader); fileNameManifest = fileNameManifest.Replace(".nef", ".manifest.json"); string manifestFile = File.ReadAllText(fileNameManifest); BuildScript buildScriptNef = new BuildNEF(neffile, manifestFile); scriptsAll[filename] = buildScriptNef; } } else { scriptsAll[filename] = NeonTestTool.BuildScript(filename, releaseMode, optimizer); } } return scriptsAll[filename]; } public BuildScript Build(string[] filenames, bool releaseMode = false, bool optimizer = true) { var key = string.Join("\n", filenames); if (scriptsAll.ContainsKey(key) == false) { return NeonTestTool.BuildScript(filenames, releaseMode, optimizer); } return scriptsAll[key]; } public void AddEntryScript(string filename, bool releaseMode = false, bool optimizer = true) { ScriptEntry = Build(filename, releaseMode, optimizer); Reset(); } public void AddEntryScript(string[] filenames, bool releaseMode = false, bool optimizer = true) { ScriptEntry = Build(filenames, releaseMode, optimizer); Reset(); } public void Reset() { this.State = VMState.BREAK; // Required for allow to reuse the same TestEngine this.InvocationStack.Clear(); while (this.ResultStack.Count > 0) { this.ResultStack.Pop(); } if (ScriptEntry != null) this.LoadScript(ScriptEntry.finalNEF); } public class ContractMethod { readonly TestEngine engine; readonly string methodname; public ContractMethod(TestEngine engine, string methodname) { this.engine = engine; this.methodname = methodname; } public StackItem Run(params StackItem[] _params) { return this.engine.ExecuteTestCaseStandard(methodname, _params).Pop(); } public EvaluationStack RunEx(params StackItem[] _params) { return this.engine.ExecuteTestCaseStandard(methodname, _params); } } public ContractMethod GetMethod(string methodname) { return new ContractMethod(this, methodname); } public int GetMethodEntryOffset(string methodname) { if (this.ScriptEntry is null) return -1; var methods = this.ScriptEntry.finalABI["methods"] as JArray; foreach (var item in methods) { var method = item as JObject; if (method["name"].AsString() == methodname) return int.Parse(method["offset"].AsString()); } return -1; } public EvaluationStack ExecuteTestCaseStandard(string methodname, params StackItem[] args) { var offset = GetMethodEntryOffset(methodname); if (offset == -1) throw new Exception("Can't find method : " + methodname); return ExecuteTestCaseStandard(offset, args); } public EvaluationStack ExecuteTestCaseStandard(int offset, params StackItem[] args) { var context = InvocationStack.Pop(); LoadContext(context.Clone(offset)); for (var i = args.Length - 1; i >= 0; i--) this.Push(args[i]); var initializeOffset = GetMethodEntryOffset("_initialize"); if (initializeOffset != -1) { LoadContext(CurrentContext.Clone(initializeOffset)); } while (true) { var bfault = (this.State & VMState.FAULT) > 0; var bhalt = (this.State & VMState.HALT) > 0; if (bfault || bhalt) break; Console.WriteLine("op:[" + this.CurrentContext.InstructionPointer.ToString("X04") + "]" + this.CurrentContext.CurrentInstruction.OpCode); this.ExecuteNext(); } return this.ResultStack; } protected override void OnFault(Exception e) { base.OnFault(e); Console.WriteLine(e.ToString()); } public EvaluationStack ExecuteTestCase(params StackItem[] args) { if (CurrentContext.InstructionPointer != 0) { var context = InvocationStack.Pop(); LoadContext(context.Clone(0)); } if (args != null) { for (var i = args.Length - 1; i >= 0; i--) { this.CurrentContext.EvaluationStack.Push(args[i]); } } while (true) { var bfault = (this.State & VMState.FAULT) > 0; var bhalt = (this.State & VMState.HALT) > 0; if (bfault || bhalt) break; Console.WriteLine("op:[" + this.CurrentContext.InstructionPointer.ToString("X04") + "]" + this.CurrentContext.CurrentInstruction.OpCode); this.ExecuteNext(); } return this.ResultStack; } public void SendTestNotification(UInt160 hash, string eventName, VM.Types.Array state) { typeof(ApplicationEngine).GetMethod("SendNotification", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) .Invoke(this, new object[] { hash, eventName, state }); } static Dictionary<uint, InteropDescriptor> callmethod; public void ClearNotifications() { typeof(ApplicationEngine).GetField("notifications", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(this, null); } protected override void OnSysCall(uint method) { if (callmethod == null) { callmethod = new Dictionary<uint, InteropDescriptor>() { { Native_Deploy.Hash , Native_Deploy } }; foreach (var m in ApplicationEngine.Services) { callmethod[m.Key] = m.Value; } } if (callmethod.ContainsKey(method) == false) { throw new Exception($"Syscall not found: {method:X2} (using base call)"); } else { base.OnSysCall(method); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Image.cs // // Authors: Christian Meyer (Christian.Meyer@cs.tum.edu) // Alexandre Pigolkine (pigolkine@gmx.de) // Jordi Mas i Hernandez (jordi@ximian.com) // Sanjay Gupta (gsanjay@novell.com) // Ravindra (rkumar@novell.com) // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2002 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com) // Copyright (C) 2013 Kristof Ralovich, changes are available under the terms of the MIT X11 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.Runtime.Serialization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Drawing.Imaging; using System.IO; using System.Reflection; namespace System.Drawing { [ComVisible(true)] [Serializable] #if !NETCORE [Editor ("System.Drawing.Design.ImageEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))] [TypeConverter (typeof(ImageConverter))] #endif [ImmutableObject(true)] public abstract class Image : MarshalByRefObject, IDisposable, ICloneable, ISerializable { public delegate bool GetThumbnailImageAbort(); private object tag; internal IntPtr nativeObject = IntPtr.Zero; // constructor internal Image() { } #if NETCORE protected Image(SerializationInfo info, StreamingContext context) #else internal Image (SerializationInfo info, StreamingContext context) #endif { foreach (SerializationEntry serEnum in info) { if (String.Compare(serEnum.Name, "Data", true) == 0) { byte[] bytes = (byte[])serEnum.Value; if (bytes != null) { MemoryStream ms = new MemoryStream(bytes); nativeObject = InitFromStream(ms); } } } } // FIXME - find out how metafiles (another decoder-only codec) are handled void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { using (MemoryStream ms = new MemoryStream()) { // Icon is a decoder-only codec if (RawFormat.Equals(ImageFormat.Icon)) { Save(ms, ImageFormat.Png); } else { Save(ms, RawFormat); } si.AddValue("Data", ms.ToArray()); } } // public methods // static public static Image FromFile(string filename) { return FromFile(filename, false); } public static Image FromFile(string filename, bool useEmbeddedColorManagement) { IntPtr imagePtr; int st; if (!File.Exists(filename)) throw new FileNotFoundException(filename); if (useEmbeddedColorManagement) st = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename, out imagePtr); else st = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename, out imagePtr); SafeNativeMethods.Gdip.CheckStatus(st); return CreateFromHandle(imagePtr); } public static Bitmap FromHbitmap(IntPtr hbitmap) { return FromHbitmap(hbitmap, IntPtr.Zero); } public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette) { IntPtr imagePtr; int st; st = SafeNativeMethods.Gdip.GdipCreateBitmapFromHBITMAP(hbitmap, hpalette, out imagePtr); SafeNativeMethods.Gdip.CheckStatus(st); return new Bitmap(imagePtr); } // note: FromStream can return either a Bitmap or Metafile instance public static Image FromStream(Stream stream) { return LoadFromStream(stream, false); } [MonoLimitation("useEmbeddedColorManagement isn't supported.")] public static Image FromStream(Stream stream, bool useEmbeddedColorManagement) { return LoadFromStream(stream, false); } // See http://support.microsoft.com/default.aspx?scid=kb;en-us;831419 for performance discussion [MonoLimitation("useEmbeddedColorManagement and validateImageData aren't supported.")] public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData) { return LoadFromStream(stream, false); } internal static Image LoadFromStream(Stream stream, bool keepAlive) { if (stream == null) throw new ArgumentNullException("stream"); Image img = CreateFromHandle(InitFromStream(stream)); return img; } internal static Image CreateImageObject(IntPtr nativeImage) { return CreateFromHandle(nativeImage); } internal static Image CreateFromHandle(IntPtr handle) { ImageType type; SafeNativeMethods.Gdip.CheckStatus(SafeNativeMethods.Gdip.GdipGetImageType(handle, out type)); switch (type) { case ImageType.Bitmap: return new Bitmap(handle); case ImageType.Metafile: return new Metafile(handle); default: throw new NotSupportedException("Unknown image type."); } } public static int GetPixelFormatSize(PixelFormat pixfmt) { int result = 0; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: result = 16; break; case PixelFormat.Format1bppIndexed: result = 1; break; case PixelFormat.Format24bppRgb: result = 24; break; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: result = 32; break; case PixelFormat.Format48bppRgb: result = 48; break; case PixelFormat.Format4bppIndexed: result = 4; break; case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = 64; break; case PixelFormat.Format8bppIndexed: result = 8; break; } return result; } public static bool IsAlphaPixelFormat(PixelFormat pixfmt) { bool result = false; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = true; break; case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format1bppIndexed: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppRgb: case PixelFormat.Format48bppRgb: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: result = false; break; } return result; } public static bool IsCanonicalPixelFormat(PixelFormat pixfmt) { return ((pixfmt & PixelFormat.Canonical) != 0); } public static bool IsExtendedPixelFormat(PixelFormat pixfmt) { return ((pixfmt & PixelFormat.Extended) != 0); } internal static IntPtr InitFromStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); IntPtr imagePtr; int st; // Seeking required if (!stream.CanSeek) { byte[] buffer = new byte[256]; int index = 0; int count; do { if (buffer.Length < index + 256) { byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, buffer.Length); buffer = newBuffer; } count = stream.Read(buffer, index, 256); index += count; } while (count != 0); stream = new MemoryStream(buffer, 0, index); } // Unix, with libgdiplus // We use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream // with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, true); st = SafeNativeMethods.Gdip.GdipLoadImageFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out imagePtr); return st == SafeNativeMethods.Gdip.Ok ? imagePtr : IntPtr.Zero; } // non-static public RectangleF GetBounds(ref GraphicsUnit pageUnit) { RectangleF source; int status = SafeNativeMethods.Gdip.GdipGetImageBounds(nativeObject, out source, ref pageUnit); SafeNativeMethods.Gdip.CheckStatus(status); return source; } public EncoderParameters GetEncoderParameterList(Guid encoder) { int status; uint sz; status = SafeNativeMethods.Gdip.GdipGetEncoderParameterListSize(nativeObject, ref encoder, out sz); SafeNativeMethods.Gdip.CheckStatus(status); IntPtr rawEPList = Marshal.AllocHGlobal((int)sz); EncoderParameters eps; try { status = SafeNativeMethods.Gdip.GdipGetEncoderParameterList(nativeObject, ref encoder, sz, rawEPList); eps = EncoderParameters.ConvertFromMemory(rawEPList); SafeNativeMethods.Gdip.CheckStatus(status); } finally { Marshal.FreeHGlobal(rawEPList); } return eps; } public int GetFrameCount(FrameDimension dimension) { uint count; Guid guid = dimension.Guid; int status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(nativeObject, ref guid, out count); SafeNativeMethods.Gdip.CheckStatus(status); return (int)count; } public PropertyItem GetPropertyItem(int propid) { int propSize; IntPtr property; PropertyItem item = new PropertyItem(); GdipPropertyItem gdipProperty = new GdipPropertyItem(); int status; status = SafeNativeMethods.Gdip.GdipGetPropertyItemSize(nativeObject, propid, out propSize); SafeNativeMethods.Gdip.CheckStatus(status); /* Get PropertyItem */ property = Marshal.AllocHGlobal(propSize); try { status = SafeNativeMethods.Gdip.GdipGetPropertyItem(nativeObject, propid, propSize, property); SafeNativeMethods.Gdip.CheckStatus(status); gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure(property, typeof(GdipPropertyItem)); GdipPropertyItem.MarshalTo(gdipProperty, item); } finally { Marshal.FreeHGlobal(property); } return item; } public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData) { if ((thumbWidth <= 0) || (thumbHeight <= 0)) throw new OutOfMemoryException("Invalid thumbnail size"); Image ThumbNail = new Bitmap(thumbWidth, thumbHeight); using (Graphics g = Graphics.FromImage(ThumbNail)) { int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(g.nativeObject, nativeObject, 0, 0, thumbWidth, thumbHeight, 0, 0, this.Width, this.Height, GraphicsUnit.Pixel, IntPtr.Zero, null, IntPtr.Zero); SafeNativeMethods.Gdip.CheckStatus(status); } return ThumbNail; } public void RemovePropertyItem(int propid) { int status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(nativeObject, propid); SafeNativeMethods.Gdip.CheckStatus(status); } public void RotateFlip(RotateFlipType rotateFlipType) { int status = SafeNativeMethods.Gdip.GdipImageRotateFlip(nativeObject, rotateFlipType); SafeNativeMethods.Gdip.CheckStatus(status); } internal ImageCodecInfo findEncoderForFormat(ImageFormat format) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo encoder = null; if (format.Guid.Equals(ImageFormat.MemoryBmp.Guid)) format = ImageFormat.Png; /* Look for the right encoder for our format*/ for (int i = 0; i < encoders.Length; i++) { if (encoders[i].FormatID.Equals(format.Guid)) { encoder = encoders[i]; break; } } return encoder; } public void Save(string filename) { Save(filename, RawFormat); } public void Save(string filename, ImageFormat format) { ImageCodecInfo encoder = findEncoderForFormat(format); if (encoder == null) { // second chance encoder = findEncoderForFormat(RawFormat); if (encoder == null) { string msg = string.Format("No codec available for saving format '{0}'.", format.Guid); throw new ArgumentException(msg, "format"); } } Save(filename, encoder, null); } public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams) { int st; Guid guid = encoder.Clsid; if (encoderParams == null) { st = SafeNativeMethods.Gdip.GdipSaveImageToFile(nativeObject, filename, ref guid, IntPtr.Zero); } else { IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveImageToFile(nativeObject, filename, ref guid, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); } SafeNativeMethods.Gdip.CheckStatus(st); } public void Save(Stream stream, ImageFormat format) { ImageCodecInfo encoder = findEncoderForFormat(format); if (encoder == null) throw new ArgumentException("No codec available for format:" + format.Guid); Save(stream, encoder, null); } public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams; Guid guid = encoder.Clsid; if (encoderParams == null) nativeEncoderParams = IntPtr.Zero; else nativeEncoderParams = encoderParams.ConvertToMemory(); try { GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); st = SafeNativeMethods.Gdip.GdipSaveImageToDelegate_linux(nativeObject, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, ref guid, nativeEncoderParams); } finally { if (nativeEncoderParams != IntPtr.Zero) Marshal.FreeHGlobal(nativeEncoderParams); } SafeNativeMethods.Gdip.CheckStatus(st); } public void SaveAdd(EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveAdd(nativeObject, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); SafeNativeMethods.Gdip.CheckStatus(st); } public void SaveAdd(Image image, EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = SafeNativeMethods.Gdip.GdipSaveAddImage(nativeObject, image.NativeObject, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); SafeNativeMethods.Gdip.CheckStatus(st); } public int SelectActiveFrame(FrameDimension dimension, int frameIndex) { Guid guid = dimension.Guid; int st = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(nativeObject, ref guid, frameIndex); SafeNativeMethods.Gdip.CheckStatus(st); return frameIndex; } public void SetPropertyItem(PropertyItem propitem) { if (propitem == null) throw new ArgumentNullException("propitem"); int nItemSize = Marshal.SizeOf(propitem.Value[0]); int size = nItemSize * propitem.Value.Length; IntPtr dest = Marshal.AllocHGlobal(size); try { GdipPropertyItem pi = new GdipPropertyItem(); pi.id = propitem.Id; pi.len = propitem.Len; pi.type = propitem.Type; Marshal.Copy(propitem.Value, 0, dest, size); pi.value = dest; unsafe { int status = SafeNativeMethods.Gdip.GdipSetPropertyItem(nativeObject, &pi); SafeNativeMethods.Gdip.CheckStatus(status); } } finally { Marshal.FreeHGlobal(dest); } } // properties [Browsable(false)] public int Flags { get { int flags; int status = SafeNativeMethods.Gdip.GdipGetImageFlags(nativeObject, out flags); SafeNativeMethods.Gdip.CheckStatus(status); return flags; } } [Browsable(false)] public Guid[] FrameDimensionsList { get { uint found; int status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(nativeObject, out found); SafeNativeMethods.Gdip.CheckStatus(status); Guid[] guid = new Guid[found]; status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(nativeObject, guid, found); SafeNativeMethods.Gdip.CheckStatus(status); return guid; } } [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Height { get { uint height; int status = SafeNativeMethods.Gdip.GdipGetImageHeight(nativeObject, out height); SafeNativeMethods.Gdip.CheckStatus(status); return (int)height; } } public float HorizontalResolution { get { float resolution; int status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(nativeObject, out resolution); SafeNativeMethods.Gdip.CheckStatus(status); return resolution; } } [Browsable(false)] public ColorPalette Palette { get { return retrieveGDIPalette(); } set { storeGDIPalette(value); } } internal ColorPalette retrieveGDIPalette() { int bytes; ColorPalette ret = new ColorPalette(); int st = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(nativeObject, out bytes); SafeNativeMethods.Gdip.CheckStatus(st); IntPtr palette_data = Marshal.AllocHGlobal(bytes); try { st = SafeNativeMethods.Gdip.GdipGetImagePalette(nativeObject, palette_data, bytes); SafeNativeMethods.Gdip.CheckStatus(st); ret.ConvertFromMemory(palette_data); return ret; } finally { Marshal.FreeHGlobal(palette_data); } } internal void storeGDIPalette(ColorPalette palette) { if (palette == null) { throw new ArgumentNullException("palette"); } IntPtr palette_data = palette.ConvertToMemory(); if (palette_data == IntPtr.Zero) { return; } try { int st = SafeNativeMethods.Gdip.GdipSetImagePalette(nativeObject, palette_data); SafeNativeMethods.Gdip.CheckStatus(st); } finally { Marshal.FreeHGlobal(palette_data); } } public SizeF PhysicalDimension { get { float width, height; int status = SafeNativeMethods.Gdip.GdipGetImageDimension(nativeObject, out width, out height); SafeNativeMethods.Gdip.CheckStatus(status); return new SizeF(width, height); } } public PixelFormat PixelFormat { get { PixelFormat pixFormat; int status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(nativeObject, out pixFormat); SafeNativeMethods.Gdip.CheckStatus(status); return pixFormat; } } [Browsable(false)] public int[] PropertyIdList { get { uint propNumbers; int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(nativeObject, out propNumbers); SafeNativeMethods.Gdip.CheckStatus(status); int[] idList = new int[propNumbers]; status = SafeNativeMethods.Gdip.GdipGetPropertyIdList(nativeObject, propNumbers, idList); SafeNativeMethods.Gdip.CheckStatus(status); return idList; } } [Browsable(false)] public PropertyItem[] PropertyItems { get { int propNums, propsSize, propSize; IntPtr properties, propPtr; PropertyItem[] items; GdipPropertyItem gdipProperty = new GdipPropertyItem(); int status; status = SafeNativeMethods.Gdip.GdipGetPropertySize(nativeObject, out propsSize, out propNums); SafeNativeMethods.Gdip.CheckStatus(status); items = new PropertyItem[propNums]; if (propNums == 0) return items; /* Get PropertyItem list*/ properties = Marshal.AllocHGlobal(propsSize * propNums); try { status = SafeNativeMethods.Gdip.GdipGetAllPropertyItems(nativeObject, propsSize, propNums, properties); SafeNativeMethods.Gdip.CheckStatus(status); propSize = Marshal.SizeOf(gdipProperty); propPtr = properties; for (int i = 0; i < propNums; i++, propPtr = new IntPtr(propPtr.ToInt64() + propSize)) { gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure (propPtr, typeof(GdipPropertyItem)); items[i] = new PropertyItem(); GdipPropertyItem.MarshalTo(gdipProperty, items[i]); } } finally { Marshal.FreeHGlobal(properties); } return items; } } public ImageFormat RawFormat { get { Guid guid; int st = SafeNativeMethods.Gdip.GdipGetImageRawFormat(nativeObject, out guid); SafeNativeMethods.Gdip.CheckStatus(st); return new ImageFormat(guid); } } public Size Size { get { return new Size(Width, Height); } } [DefaultValue(null)] [LocalizableAttribute(false)] #if !NETCORE [BindableAttribute(true)] [TypeConverter (typeof (StringConverter))] #endif public object Tag { get { return tag; } set { tag = value; } } public float VerticalResolution { get { float resolution; int status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(nativeObject, out resolution); SafeNativeMethods.Gdip.CheckStatus(status); return resolution; } } [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Width { get { uint width; int status = SafeNativeMethods.Gdip.GdipGetImageWidth(nativeObject, out width); SafeNativeMethods.Gdip.CheckStatus(status); return (int)width; } } internal IntPtr NativeObject { get { return nativeObject; } set { nativeObject = value; } } internal IntPtr nativeImage { get { return nativeObject; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Image() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (nativeObject != IntPtr.Zero) { int status = SafeNativeMethods.Gdip.GdipDisposeImage(nativeObject); // ... set nativeObject to null before (possibly) throwing an exception nativeObject = IntPtr.Zero; SafeNativeMethods.Gdip.CheckStatus(status); } } public object Clone() { IntPtr newimage = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneImage(NativeObject, out newimage); SafeNativeMethods.Gdip.CheckStatus(status); if (this is Bitmap) return new Bitmap(newimage); else return new Metafile(newimage); } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Base class for all Roslyn light bulb menu items. /// </summary> internal partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction, IEquatable<ISuggestedAction> { protected readonly IAsynchronousOperationListener OperationListener; protected readonly Workspace Workspace; protected readonly ITextBuffer SubjectBuffer; protected readonly ICodeActionEditHandlerService EditHandler; protected readonly object Provider; internal readonly CodeAction CodeAction; private readonly ImmutableArray<SuggestedActionSet> _actionSets; protected readonly IWaitIndicator WaitIndicator; internal SuggestedAction( Workspace workspace, ITextBuffer subjectBuffer, ICodeActionEditHandlerService editHandler, IWaitIndicator waitIndicator, CodeAction codeAction, object provider, IAsynchronousOperationListener operationListener, IEnumerable<SuggestedActionSet> actionSets = null) { Contract.ThrowIfTrue(provider == null); this.Workspace = workspace; this.SubjectBuffer = subjectBuffer; this.CodeAction = codeAction; this.EditHandler = editHandler; this.WaitIndicator = waitIndicator; this.Provider = provider; OperationListener = operationListener; _actionSets = actionSets.AsImmutableOrEmpty(); } internal virtual CodeActionPriority Priority => CodeAction?.Priority ?? CodeActionPriority.Medium; public bool TryGetTelemetryId(out Guid telemetryId) { // TODO: this is temporary. Diagnostic team needs to figure out how to provide unique id per a fix. // for now, we will use type of CodeAction, but there are some predefined code actions that are used by multiple fixes // and this will not distinguish those // AssemblyQualifiedName will change across version numbers, FullName won't var type = CodeAction.GetType(); type = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; telemetryId = new Guid(type.FullName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return true; } // NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread. protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetOperationsAsync(progressTracker, cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken) { return Task.Run( async () => await actionWithOptions.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken); } public void Invoke(CancellationToken cancellationToken) { this.AssertIsForeground(); // Create a task to do the actual async invocation of this action. // For testing purposes mark that we still have an outstanding async // operation so that we don't try to validate things too soon. var asyncToken = OperationListener.BeginAsyncOperation(GetType().Name + "." + nameof(Invoke)); var task = YieldThenInvokeAsync(cancellationToken); task.CompletesAsyncOperation(asyncToken); } private async Task YieldThenInvokeAsync(CancellationToken cancellationToken) { this.AssertIsForeground(); // Yield the UI thread so that the light bulb can be dismissed. This is necessary // as some code actions may be long running, and we don't want the light bulb to // stay on screen. await Task.Yield(); // Always wrap whatever we're doing in a threaded wait dialog. using (var context = this.WaitIndicator.StartWait(CodeAction.Title, CodeAction.Message, allowCancel: true, showProgress: true)) using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken)) { this.AssertIsForeground(); // Then proceed and actually do the invoke. await InvokeAsync(context.ProgressTracker, linkedSource.Token).ConfigureAwait(true); } } protected virtual async Task InvokeAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { this.AssertIsForeground(); var snapshot = this.SubjectBuffer.CurrentSnapshot; using (new CaretPositionRestorer(this.SubjectBuffer, this.EditHandler.AssociatedViewService)) { Func<Document> getFromDocument = () => this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); await InvokeCoreAsync(getFromDocument, progressTracker, cancellationToken).ConfigureAwait(true); } } protected async Task InvokeCoreAsync( Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken) { this.AssertIsForeground(); var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); await extensionManager.PerformActionAsync(Provider, async () => { await InvokeWorkerAsync(getFromDocument, progressTracker, cancellationToken).ConfigureAwait(false); }).ConfigureAwait(true); } private async Task InvokeWorkerAsync( Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken) { this.AssertIsForeground(); IEnumerable<CodeActionOperation> operations = null; // NOTE: As mentioned above, we want to avoid computing the operations on the UI thread. // However, for CodeActionWithOptions, GetOptions() might involve spinning up a dialog // to compute the options and must be done on the UI thread. var actionWithOptions = this.CodeAction as CodeActionWithOptions; if (actionWithOptions != null) { var options = actionWithOptions.GetOptions(cancellationToken); if (options != null) { operations = await GetOperationsAsync(actionWithOptions, options, cancellationToken).ConfigureAwait(true); this.AssertIsForeground(); } } else { operations = await GetOperationsAsync(progressTracker, cancellationToken).ConfigureAwait(true); this.AssertIsForeground(); } if (operations != null) { // Clear the progress we showed while computing the action. // We'll now show progress as we apply the action. progressTracker.Clear(); EditHandler.Apply(Workspace, getFromDocument(), operations, CodeAction.Title, progressTracker, cancellationToken); } } public string DisplayText { get { // Underscores will become an accelerator in the VS smart tag. So we double all // underscores so they actually get represented as an underscore in the UI. var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, defaultValue: string.Empty); return text.Replace("_", "__"); } } protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We will always invoke this from the UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true); return EditHandler.GetPreviews(Workspace, operations, cancellationToken); } public virtual bool HasPreview { get { // HasPreview is called synchronously on the UI thread. In order to avoid blocking the UI thread, // we need to provide a 'quick' answer here as opposed to the 'right' answer. Providing the 'right' // answer is expensive (because we will need to call CodeAction.GetPreviewOperationsAsync() for this // and this will involve computing the changed solution for the ApplyChangesOperation for the fix / // refactoring). So we always return 'true' here (so that platform will call GetActionSetsAsync() // below). Platform guarantees that nothing bad will happen if we return 'true' here and later return // 'null' / empty collection from within GetPreviewAsync(). return true; } } public virtual async Task<object> GetPreviewAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Light bulb will always invoke this function on the UI thread. AssertIsForeground(); var previewPaneService = Workspace.Services.GetService<IPreviewPaneService>(); if (previewPaneService == null) { return null; } // after this point, this method should only return at GetPreviewPane. otherwise, DifferenceViewer will leak // since there is no one to close the viewer var preferredDocumentId = Workspace.GetDocumentIdInCurrentContext(SubjectBuffer.AsTextContainer()); var preferredProjectId = preferredDocumentId?.ProjectId; var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var previewContents = await extensionManager.PerformFunctionAsync(Provider, async () => { // We need to stay on UI thread after GetPreviewResultAsync() so that TakeNextPreviewAsync() // below can execute on UI thread. We use ConfigureAwait(true) to stay on the UI thread. var previewResult = await GetPreviewResultAsync(cancellationToken).ConfigureAwait(true); if (previewResult == null) { return null; } else { // TakeNextPreviewAsync() needs to run on UI thread. AssertIsForeground(); return await previewResult.GetPreviewsAsync(preferredDocumentId, preferredProjectId, cancellationToken).ConfigureAwait(true); } // GetPreviewPane() below needs to run on UI thread. We use ConfigureAwait(true) to stay on the UI thread. }, defaultValue: null).ConfigureAwait(true); // GetPreviewPane() needs to run on the UI thread. AssertIsForeground(); string language; string projectType; Workspace.GetLanguageAndProjectType(preferredProjectId, out language, out projectType); return previewPaneService.GetPreviewPane(GetDiagnostic(), language, projectType, previewContents); } protected virtual DiagnosticData GetDiagnostic() { return null; } public virtual bool HasActionSets => _actionSets.Length > 0; public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken) { return Task.FromResult<IEnumerable<SuggestedActionSet>>(GetActionSets()); } internal ImmutableArray<SuggestedActionSet> GetActionSets() { return _actionSets; } #region not supported void IDisposable.Dispose() { // do nothing } // same as display text string ISuggestedAction.IconAutomationText => DisplayText; ImageMoniker ISuggestedAction.IconMoniker { get { if (CodeAction.Glyph.HasValue) { var imageService = Workspace.Services.GetService<IImageMonikerService>(); return imageService.GetImageMoniker((Glyph)CodeAction.Glyph.Value); } return default(ImageMoniker); } } string ISuggestedAction.InputGestureText { get { // no shortcut support return null; } } #endregion #region IEquatable<ISuggestedAction> public bool Equals(ISuggestedAction other) { return Equals(other as SuggestedAction); } public override bool Equals(object obj) { return Equals(obj as SuggestedAction); } internal bool Equals(SuggestedAction otherSuggestedAction) { if (otherSuggestedAction == null) { return false; } if (ReferenceEquals(this, otherSuggestedAction)) { return true; } if (!ReferenceEquals(Provider, otherSuggestedAction.Provider)) { return false; } var otherCodeAction = otherSuggestedAction.CodeAction; if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null) { return false; } return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey; } public override int GetHashCode() { if (CodeAction.EquivalenceKey == null) { return base.GetHashCode(); } return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode()); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Text; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Location.Paths { /// <summary> /// Location Paths - MiscWithEncodings /// </summary> public class MiscWithEncodingTests { public MiscWithEncodingTests() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } /// <summary> /// Return all OrderDate's equal to ""11/16/94"". /// OrderIDs/CustomerIDs/EmployeeIDs/OrderDates/OrderDate[.="11/16/94"] /// </summary> [Fact] public void AbbreviatedSyntaxTest125() { var xml = "XQL_Orders_j1.xml"; var testExpression = @"OrderIDs/CustomerIDs/EmployeeIDs/OrderDates/OrderDate[.='11/16/94']"; var expected = new XPathResult(0); Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Russian: xpath testing problem char, return 1 node /// </summary> [Fact] public void GlobalizationTest5612() { var xml = "Russian_problem_chars.xml"; var testExpression = "//root[contains(text(), \"?? \u00A4 ?? ?? \u00A9 ? \u00AE ??\")]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "root", Name = "root", HasNameTable = true, Value = "\n?? \u00A4 ?? ?? \u00A9 ? \u00AE ?? \n" }); Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Testing multiple predicates - Return all CustomerIDs that have a Customer ID and EmployeeIDs with an EmployeeID and a Freight equal to 12.75. /// OrderIDs/CustomerIDs[CustomerID]/EmployeeIDs[EmployeeID][OrderDates/Freight=12.75] /// </summary> [Fact] public void MatchesTest1136() { var xml = "XQL_Orders_j3.xml"; var startingNodePath = "//EmployeeIDs[1]"; var testExpression = @"OrderIDs/CustomerIDs[CustomerID]/EmployeeIDs[EmployeeID][OrderDates/Freight=12.75]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Using a very large number for position - Return the 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999th CustomerIDs (Should return nothing) /// OrderIDs/CustomerIDs[9999999999999999999999999999999999999999999999999999999999999999999999999999999999999] /// </summary> [Fact] public void MatchesTest1137() { var xml = "XQL_Orders_j3.xml"; var startingNodePath = "//CustomerIDs"; var testExpression = @"OrderIDs/CustomerIDs[9999999999999999999999999999999999999999999999999999999999999999999999999999999999999]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Predicates containing attribute - Return all OrderIDs CollatingOrder attribute greater than or equal to 1033. /// /ROOT/OrderIDs[OrderID/@CollatingOrder>=1033]/OrderID/@CollatingOrder /// </summary> [Fact] public void MatchesTest1138() { var xml = "xql_orders-flat-200a.xml"; var startingNodePath = "/ROOT/OrderIDs[22]/OrderID/@CollatingOrder"; var testExpression = @"/ROOT/OrderIDs[OrderID/@CollatingOrder>=1033]/OrderID/@CollatingOrder"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Multiple predicates - Return all OrderIDs where CustomerID's have an EmployeeIDs and EmployeeID equal to 3 and an OrderDate greater than or equal to ""11/16/94"". /// .//OrderIDs[CustomerIDs[EmployeeIDs][//EmployeeID='3']][//OrderDate>='11/16/94'] /// </summary> [Fact] public void PredicatesTest1038() { var xml = "XQL_Orders_j3.xml"; var startingNodePath = "/ROOT"; var testExpression = @".//OrderIDs[CustomerIDs[EmployeeIDs][//EmployeeID='3']][//OrderDate>='11/16/94']"; var expected = new XPathResult(0); Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Testing multiple predicates - Return all CustomerIDs that have a Customer ID and EmployeeIDs with an EmployeeID and a Freight equal to 12.75. /// OrderIDs/CustomerIDs[CustomerID]/EmployeeIDs[EmployeeID][OrderDates/Freight=12.75] /// </summary> [Fact] public void PredicatesTest1039() { var xml = "XQL_Orders_j3.xml"; var startingNodePath = "/ROOT"; var testExpression = @"OrderIDs/CustomerIDs[CustomerID]/EmployeeIDs[EmployeeID][OrderDates/Freight=12.75]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "EmployeeIDs", Name = "EmployeeIDs", HasNameTable = true, Value = "\n\t\t\t\t3\n\t\t\t\t\n\t\t\t\t\t11/16/94\n\t\t\t\t\t12/14/94\n\t\t\t\t\t11/28/94\n\t\t\t\t\t1\n\t\t\t\t\t12.75\n\t\t\t\t\tLILA-Supermercado\n\t\t\t\t\tCarrera 52 con Ave. Bol\u00EDvar #65-98 Llano Largo\n\t\t\t\t\tBarquisimeto\n\t\t\t\t\tLara\n\t\t\t\t\t3508\n\t\t\t\t\tVenezuela\n\t\t\t\t\n\t\t\t" }); Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Using a very large number for position - Return the 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999th CustomerIDs (Should return nothing) /// OrderIDs/CustomerIDs[9999999999999999999999999999999999999999999999999999999999999999999999999999999999999] /// </summary> [Fact] public void PredicatesTest1040() { var xml = "XQL_Orders_j1.xml"; var startingNodePath = "/ROOT"; var testExpression = @"OrderIDs/CustomerIDs[9999999999999999999999999999999999999999999999999999999999999999999999999999999999999]"; var expected = new XPathResult(0); Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Predicates containing attribute - Return all OrderIDs CollatingOrder attribute greater than or equal to 1033. /// /ROOT/OrderIDs[OrderID/@CollatingOrder>=1033]/OrderID/@CollatingOrder /// </summary> [Fact] public void PredicatesTest1041() { var xml = "xql_orders-flat-200a.xml"; var testExpression = @"/ROOT/OrderIDs[OrderID/@CollatingOrder>=1033]/OrderID/@CollatingOrder"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1034" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1034" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1034" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "CollatingOrder", Name = "CollatingOrder", HasNameTable = true, Value = "1033" }); Utils.XPathNodesetTest(xml, testExpression, expected); } } }
// 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.Threading.Tasks; using System.Xml.Schema; namespace System.Xml { internal class XmlAsyncCheckReader : XmlReader { private readonly XmlReader _coreReader = null; private Task _lastTask = Task.CompletedTask; internal XmlReader CoreReader { get { return _coreReader; } } public static XmlAsyncCheckReader CreateAsyncCheckWrapper(XmlReader reader) { if (reader is IXmlLineInfo) { if (reader is IXmlNamespaceResolver) { return new XmlAsyncCheckReaderWithLineInfoNS(reader); } return new XmlAsyncCheckReaderWithLineInfo(reader); } else if (reader is IXmlNamespaceResolver) { return new XmlAsyncCheckReaderWithNS(reader); } return new XmlAsyncCheckReader(reader); } public XmlAsyncCheckReader(XmlReader reader) { _coreReader = reader; } private void CheckAsync() { if (!_lastTask.IsCompleted) { throw new InvalidOperationException(SR.Xml_AsyncIsRunningException); } } #region Sync Methods, Properties Check public override XmlReaderSettings Settings { get { XmlReaderSettings settings = _coreReader.Settings; if (null != settings) { settings = settings.Clone(); } else { settings = new XmlReaderSettings(); } settings.Async = true; settings.ReadOnly = true; return settings; } } public override XmlNodeType NodeType { get { CheckAsync(); return _coreReader.NodeType; } } public override string Name { get { CheckAsync(); return _coreReader.Name; } } public override string LocalName { get { CheckAsync(); return _coreReader.LocalName; } } public override string NamespaceURI { get { CheckAsync(); return _coreReader.NamespaceURI; } } public override string Prefix { get { CheckAsync(); return _coreReader.Prefix; } } public override bool HasValue { get { CheckAsync(); return _coreReader.HasValue; } } public override string Value { get { CheckAsync(); return _coreReader.Value; } } public override int Depth { get { CheckAsync(); return _coreReader.Depth; } } public override string BaseURI { get { CheckAsync(); return _coreReader.BaseURI; } } public override bool IsEmptyElement { get { CheckAsync(); return _coreReader.IsEmptyElement; } } public override bool IsDefault { get { CheckAsync(); return _coreReader.IsDefault; } } public override XmlSpace XmlSpace { get { CheckAsync(); return _coreReader.XmlSpace; } } public override string XmlLang { get { CheckAsync(); return _coreReader.XmlLang; } } public override System.Type ValueType { get { CheckAsync(); return _coreReader.ValueType; } } public override object ReadContentAsObject() { CheckAsync(); return _coreReader.ReadContentAsObject(); } public override bool ReadContentAsBoolean() { CheckAsync(); return _coreReader.ReadContentAsBoolean(); } public override double ReadContentAsDouble() { CheckAsync(); return _coreReader.ReadContentAsDouble(); } public override float ReadContentAsFloat() { CheckAsync(); return _coreReader.ReadContentAsFloat(); } public override decimal ReadContentAsDecimal() { CheckAsync(); return _coreReader.ReadContentAsDecimal(); } public override int ReadContentAsInt() { CheckAsync(); return _coreReader.ReadContentAsInt(); } public override long ReadContentAsLong() { CheckAsync(); return _coreReader.ReadContentAsLong(); } public override string ReadContentAsString() { CheckAsync(); return _coreReader.ReadContentAsString(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { CheckAsync(); return _coreReader.ReadContentAs(returnType, namespaceResolver); } public override object ReadElementContentAsObject() { CheckAsync(); return _coreReader.ReadElementContentAsObject(); } public override object ReadElementContentAsObject(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsObject(localName, namespaceURI); } public override bool ReadElementContentAsBoolean() { CheckAsync(); return _coreReader.ReadElementContentAsBoolean(); } public override bool ReadElementContentAsBoolean(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsBoolean(localName, namespaceURI); } public override DateTimeOffset ReadContentAsDateTimeOffset() { CheckAsync(); return _coreReader.ReadContentAsDateTimeOffset(); } public override double ReadElementContentAsDouble() { CheckAsync(); return _coreReader.ReadElementContentAsDouble(); } public override double ReadElementContentAsDouble(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsDouble(localName, namespaceURI); } public override float ReadElementContentAsFloat() { CheckAsync(); return _coreReader.ReadElementContentAsFloat(); } public override float ReadElementContentAsFloat(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsFloat(localName, namespaceURI); } public override decimal ReadElementContentAsDecimal() { CheckAsync(); return _coreReader.ReadElementContentAsDecimal(); } public override decimal ReadElementContentAsDecimal(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsDecimal(localName, namespaceURI); } public override int ReadElementContentAsInt() { CheckAsync(); return _coreReader.ReadElementContentAsInt(); } public override int ReadElementContentAsInt(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsInt(localName, namespaceURI); } public override long ReadElementContentAsLong() { CheckAsync(); return _coreReader.ReadElementContentAsLong(); } public override long ReadElementContentAsLong(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsLong(localName, namespaceURI); } public override string ReadElementContentAsString() { CheckAsync(); return _coreReader.ReadElementContentAsString(); } public override string ReadElementContentAsString(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAsString(localName, namespaceURI); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { CheckAsync(); return _coreReader.ReadElementContentAs(returnType, namespaceResolver); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } public override int AttributeCount { get { CheckAsync(); return _coreReader.AttributeCount; } } public override string GetAttribute(string name) { CheckAsync(); return _coreReader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { CheckAsync(); return _coreReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { CheckAsync(); return _coreReader.GetAttribute(i); } public override string this[int i] { get { CheckAsync(); return _coreReader[i]; } } public override string this[string name] { get { CheckAsync(); return _coreReader[name]; } } public override string this[string name, string namespaceURI] { get { CheckAsync(); return _coreReader[name, namespaceURI]; } } public override bool MoveToAttribute(string name) { CheckAsync(); return _coreReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { CheckAsync(); return _coreReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { CheckAsync(); _coreReader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { CheckAsync(); return _coreReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { CheckAsync(); return _coreReader.MoveToNextAttribute(); } public override bool MoveToElement() { CheckAsync(); return _coreReader.MoveToElement(); } public override bool ReadAttributeValue() { CheckAsync(); return _coreReader.ReadAttributeValue(); } public override bool Read() { CheckAsync(); return _coreReader.Read(); } public override bool EOF { get { CheckAsync(); return _coreReader.EOF; } } public override ReadState ReadState { get { CheckAsync(); return _coreReader.ReadState; } } public override void Skip() { CheckAsync(); _coreReader.Skip(); } public override XmlNameTable NameTable { get { CheckAsync(); return _coreReader.NameTable; } } public override string LookupNamespace(string prefix) { CheckAsync(); return _coreReader.LookupNamespace(prefix); } public override bool CanResolveEntity { get { CheckAsync(); return _coreReader.CanResolveEntity; } } public override void ResolveEntity() { CheckAsync(); _coreReader.ResolveEntity(); } public override bool CanReadBinaryContent { get { CheckAsync(); return _coreReader.CanReadBinaryContent; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { CheckAsync(); return _coreReader.ReadContentAsBase64(buffer, index, count); } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { CheckAsync(); return _coreReader.ReadElementContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { CheckAsync(); return _coreReader.ReadContentAsBinHex(buffer, index, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { CheckAsync(); return _coreReader.ReadElementContentAsBinHex(buffer, index, count); } public override bool CanReadValueChunk { get { CheckAsync(); return _coreReader.CanReadValueChunk; } } public override int ReadValueChunk(char[] buffer, int index, int count) { CheckAsync(); return _coreReader.ReadValueChunk(buffer, index, count); } public override XmlNodeType MoveToContent() { CheckAsync(); return _coreReader.MoveToContent(); } public override void ReadStartElement() { CheckAsync(); _coreReader.ReadStartElement(); } public override void ReadStartElement(string name) { CheckAsync(); _coreReader.ReadStartElement(name); } public override void ReadStartElement(string localname, string ns) { CheckAsync(); _coreReader.ReadStartElement(localname, ns); } public override void ReadEndElement() { CheckAsync(); _coreReader.ReadEndElement(); } public override bool IsStartElement() { CheckAsync(); return _coreReader.IsStartElement(); } public override bool IsStartElement(string name) { CheckAsync(); return _coreReader.IsStartElement(name); } public override bool IsStartElement(string localname, string ns) { CheckAsync(); return _coreReader.IsStartElement(localname, ns); } public override bool ReadToFollowing(string name) { CheckAsync(); return _coreReader.ReadToFollowing(name); } public override bool ReadToFollowing(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadToFollowing(localName, namespaceURI); } public override bool ReadToDescendant(string name) { CheckAsync(); return _coreReader.ReadToDescendant(name); } public override bool ReadToDescendant(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadToDescendant(localName, namespaceURI); } public override bool ReadToNextSibling(string name) { CheckAsync(); return _coreReader.ReadToNextSibling(name); } public override bool ReadToNextSibling(string localName, string namespaceURI) { CheckAsync(); return _coreReader.ReadToNextSibling(localName, namespaceURI); } public override string ReadInnerXml() { CheckAsync(); return _coreReader.ReadInnerXml(); } public override string ReadOuterXml() { CheckAsync(); return _coreReader.ReadOuterXml(); } public override XmlReader ReadSubtree() { CheckAsync(); XmlReader subtreeReader = _coreReader.ReadSubtree(); return CreateAsyncCheckWrapper(subtreeReader); } public override bool HasAttributes { get { CheckAsync(); return _coreReader.HasAttributes; } } protected override void Dispose(bool disposing) { CheckAsync(); //since it is protected method, we can't call coreReader.Dispose(disposing). //Internal, it is always called to Dipose(true). So call coreReader.Dispose() is OK. _coreReader.Dispose(); } #endregion #region Async Methods public override Task<string> GetValueAsync() { CheckAsync(); var task = _coreReader.GetValueAsync(); _lastTask = task; return task; } public override Task<object> ReadContentAsObjectAsync() { CheckAsync(); var task = _coreReader.ReadContentAsObjectAsync(); _lastTask = task; return task; } public override Task<string> ReadContentAsStringAsync() { CheckAsync(); var task = _coreReader.ReadContentAsStringAsync(); _lastTask = task; return task; } public override Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { CheckAsync(); var task = _coreReader.ReadContentAsAsync(returnType, namespaceResolver); _lastTask = task; return task; } public override Task<object> ReadElementContentAsObjectAsync() { CheckAsync(); var task = _coreReader.ReadElementContentAsObjectAsync(); _lastTask = task; return task; } public override Task<string> ReadElementContentAsStringAsync() { CheckAsync(); var task = _coreReader.ReadElementContentAsStringAsync(); _lastTask = task; return task; } public override Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { CheckAsync(); var task = _coreReader.ReadElementContentAsAsync(returnType, namespaceResolver); _lastTask = task; return task; } public override Task<bool> ReadAsync() { CheckAsync(); var task = _coreReader.ReadAsync(); _lastTask = task; return task; } public override Task SkipAsync() { CheckAsync(); var task = _coreReader.SkipAsync(); _lastTask = task; return task; } public override Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreReader.ReadContentAsBase64Async(buffer, index, count); _lastTask = task; return task; } public override Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreReader.ReadElementContentAsBase64Async(buffer, index, count); _lastTask = task; return task; } public override Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreReader.ReadContentAsBinHexAsync(buffer, index, count); _lastTask = task; return task; } public override Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreReader.ReadElementContentAsBinHexAsync(buffer, index, count); _lastTask = task; return task; } public override Task<int> ReadValueChunkAsync(char[] buffer, int index, int count) { CheckAsync(); var task = _coreReader.ReadValueChunkAsync(buffer, index, count); _lastTask = task; return task; } public override Task<XmlNodeType> MoveToContentAsync() { CheckAsync(); var task = _coreReader.MoveToContentAsync(); _lastTask = task; return task; } public override Task<string> ReadInnerXmlAsync() { CheckAsync(); var task = _coreReader.ReadInnerXmlAsync(); _lastTask = task; return task; } public override Task<string> ReadOuterXmlAsync() { CheckAsync(); var task = _coreReader.ReadOuterXmlAsync(); _lastTask = task; return task; } #endregion } internal class XmlAsyncCheckReaderWithNS : XmlAsyncCheckReader, IXmlNamespaceResolver { private readonly IXmlNamespaceResolver _readerAsIXmlNamespaceResolver; public XmlAsyncCheckReaderWithNS(XmlReader reader) : base(reader) { _readerAsIXmlNamespaceResolver = (IXmlNamespaceResolver)reader; } #region IXmlNamespaceResolver members IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName); } #endregion } internal class XmlAsyncCheckReaderWithLineInfo : XmlAsyncCheckReader, IXmlLineInfo { private readonly IXmlLineInfo _readerAsIXmlLineInfo; public XmlAsyncCheckReaderWithLineInfo(XmlReader reader) : base(reader) { _readerAsIXmlLineInfo = (IXmlLineInfo)reader; } #region IXmlLineInfo members public virtual bool HasLineInfo() { return _readerAsIXmlLineInfo.HasLineInfo(); } public virtual int LineNumber { get { return _readerAsIXmlLineInfo.LineNumber; } } public virtual int LinePosition { get { return _readerAsIXmlLineInfo.LinePosition; } } #endregion } internal class XmlAsyncCheckReaderWithLineInfoNS : XmlAsyncCheckReaderWithLineInfo, IXmlNamespaceResolver { private readonly IXmlNamespaceResolver _readerAsIXmlNamespaceResolver; public XmlAsyncCheckReaderWithLineInfoNS(XmlReader reader) : base(reader) { _readerAsIXmlNamespaceResolver = (IXmlNamespaceResolver)reader; } #region IXmlNamespaceResolver members IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName); } #endregion } }
//! \file ArcEAGLS.cs //! \date Fri May 15 02:52:04 2015 //! \brief EAGLS system resource archives. // // Copyright (C) 2015-2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text; using GameRes.Formats.Strings; using GameRes.Utility; namespace GameRes.Formats.Eagls { [Export(typeof(ArchiveFormat))] public class PakOpener : ArchiveFormat { public override string Tag { get { return "PAK/EAGLS"; } } public override string Description { get { return "EAGLS engine resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public PakOpener () { Extensions = new string[] { "pak" }; } internal static readonly string IndexKey = "1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik,9ol.0p;/-@:^[]"; internal static readonly byte[] EaglsKey = Encoding.ASCII.GetBytes ("EAGLS_SYSTEM"); internal static readonly byte[] AdvSysKey = Encoding.ASCII.GetBytes ("ADVSYS"); public override ArcFile TryOpen (ArcView file) { if (file.Name.HasExtension (".idx")) return null; string idx_name = Path.ChangeExtension (file.Name, ".idx"); if (!VFS.FileExists (idx_name)) return null; var idx_entry = VFS.FindFile (idx_name); if (idx_entry.Size > 0xfffff || idx_entry.Size < 10000) return null; byte[] index; using (var idx = VFS.OpenView (idx_entry)) index = DecryptIndex (idx); int index_offset = 0; int entry_size = index.Length / 10000; if (entry_size > 40) entry_size = 40; bool long_offsets = 40 == entry_size; int name_size = long_offsets ? 0x18 : 0x14; long first_offset = LittleEndian.ToUInt32 (index, name_size); bool has_scripts = false; var dir = new List<Entry>(); while (index_offset < index.Length) { if (0 == index[index_offset]) break; var name = Binary.GetCString (index, index_offset, name_size); index_offset += name_size; var entry = FormatCatalog.Instance.Create<Entry> (name); if (name.HasExtension ("dat")) { entry.Type = "script"; has_scripts = true; } if (long_offsets) { entry.Offset = LittleEndian.ToInt64 (index, index_offset) - first_offset; entry.Size = LittleEndian.ToUInt32 (index, index_offset+8); index_offset += 0x10; } else { entry.Offset = LittleEndian.ToUInt32 (index, index_offset) - first_offset; entry.Size = LittleEndian.ToUInt32 (index, index_offset+4); index_offset += 8; } if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } if (0 == dir.Count) return null; if (dir[0].Name.HasExtension ("gr")) // CG archive { var rng = DetectEncryptionScheme (file, dir[0]); if (rng != null) return new EaglsArchive (file, this, dir, new CgEncryption (rng)); } else if (has_scripts) { var enc = QueryEncryption(); if (enc != null) return new EaglsArchive (file, this, dir, enc); } return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var earc = arc as EaglsArchive; if (null == earc || !entry.Name.HasAnyOfExtensions ("dat", "gr")) return arc.File.CreateStream (entry.Offset, entry.Size); return earc.DecryptEntry (entry); } byte[] DecryptIndex (ArcView idx) { int idx_size = (int)idx.MaxOffset-4; byte[] output = new byte[idx_size]; using (var view = idx.CreateViewAccessor (0, (uint)idx.MaxOffset)) unsafe { var rng = new CRuntimeRandomGenerator(); rng.SRand (view.ReadInt32 (idx_size)); byte* ptr = view.GetPointer (0); try { for (int i = 0; i < idx_size; ++i) { output[i] = (byte)(ptr[i] ^ IndexKey[rng.Rand() % IndexKey.Length]); } return output; } finally { view.SafeMemoryMappedViewHandle.ReleasePointer(); } } } IRandomGenerator DetectEncryptionScheme (ArcView file, Entry first_entry) { int signature = (file.View.ReadInt32 (first_entry.Offset) >> 8) & 0xFFFF; if (0x4D42 == signature) // 'BM' return null; byte seed = file.View.ReadByte (first_entry.Offset+first_entry.Size-1); IRandomGenerator[] rng_list = { new LehmerRandomGenerator(), new CRuntimeRandomGenerator(), }; foreach (var rng in rng_list) { rng.SRand (seed); rng.Rand(); // skip LZSS control byte int test = signature; test ^= EaglsKey[rng.Rand() % EaglsKey.Length]; test ^= EaglsKey[rng.Rand() % EaglsKey.Length] << 8; // FIXME // as key is rather short, this detection could produce false results sometimes if (0x4D42 == test) // 'BM' return rng; } throw new UnknownEncryptionScheme(); } public override ResourceOptions GetDefaultOptions () { IEntryEncryption enc = null; if (!string.IsNullOrEmpty (Properties.Settings.Default.EAGLSEncryption)) KnownSchemes.TryGetValue (Properties.Settings.Default.EAGLSEncryption, out enc); return new EaglsOptions { Encryption = enc }; } public override object GetAccessWidget () { return new GUI.WidgetEAGLS(); } IEntryEncryption QueryEncryption () { var options = Query<EaglsOptions> (arcStrings.ArcEncryptedNotice); return options.Encryption; } internal static Dictionary<string, IEntryEncryption> KnownSchemes = new Dictionary<string, IEntryEncryption> { { "EAGLS", new EaglsEncryption() }, { "AdvSys", new AdvSysEncryption() }, }; } public class EaglsOptions : ResourceOptions { public IEntryEncryption Encryption; } public interface IRandomGenerator { void SRand (int seed); int Rand (); } [Serializable] public class CRuntimeRandomGenerator : IRandomGenerator { uint m_seed; public void SRand (int seed) { m_seed = (uint)seed; } public int Rand () { m_seed = m_seed * 214013u + 2531011u; return (int)(m_seed >> 16) & 0x7FFF; } } [Serializable] public class LehmerRandomGenerator : IRandomGenerator { int m_seed; const int A = 48271; const int Q = 44488; const int R = 3399; const int M = 2147483647; public void SRand (int seed) { m_seed = seed ^ 123459876; } public int Rand () { m_seed = A * (m_seed % Q) - R * (m_seed / Q); if (m_seed < 0) m_seed += M; return (int)(m_seed * 4.656612875245797e-10 * 256); } } public interface IEntryEncryption { void Decrypt (byte[] data); } [Serializable] public class CgEncryption : IEntryEncryption { readonly byte[] Key = PakOpener.EaglsKey; readonly IRandomGenerator m_rng; public CgEncryption (IRandomGenerator rng) { m_rng = rng; } public void Decrypt (byte[] data) { m_rng.SRand (data[data.Length-1]); int limit = Math.Min (data.Length-1, 0x174b); for (int i = 0; i < limit; ++i) { data[i] ^= (byte)Key[m_rng.Rand() % Key.Length]; } } } [Serializable] public class EaglsEncryption : IEntryEncryption { readonly byte[] Key = PakOpener.EaglsKey; readonly IRandomGenerator m_rng; public EaglsEncryption () { m_rng = new CRuntimeRandomGenerator(); } public void Decrypt (byte[] data) { int text_offset = 3600; int text_length = data.Length - text_offset - 2; m_rng.SRand ((sbyte)data[data.Length-1]); for (int i = 0; i < text_length; i += 2) { data[text_offset + i] ^= Key[m_rng.Rand() % Key.Length]; } } } [Serializable] public class AdvSysEncryption : IEntryEncryption { readonly byte[] Key = PakOpener.AdvSysKey; public void Decrypt (byte[] data) { int text_offset = 136000; int text_length = data.Length - text_offset; for (int i = 0; i < text_length; ++i) { data[text_offset + i] ^= Key[i % Key.Length]; } } } internal class EaglsArchive : ArcFile { readonly IEntryEncryption Encryption; public EaglsArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, IEntryEncryption enc) : base (arc, impl, dir) { Encryption = enc; } public Stream DecryptEntry (Entry entry) { byte[] input = File.View.ReadBytes (entry.Offset, entry.Size); Encryption.Decrypt (input); return new BinMemoryStream (input, entry.Name); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // 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 [assembly: Elmah.Scc("$Id: ErrorXml.cs 776 2011-01-12 21:09:24Z azizatif $")] namespace Elmah { #region Imports using System; using System.IO; using System.Xml; using NameValueCollection = System.Collections.Specialized.NameValueCollection; #endregion /// <summary> /// Responsible for encoding and decoding the XML representation of /// an <see cref="Error"/> object. /// </summary> public static class ErrorXml { /// <summary> /// Decodes an <see cref="Error"/> object from its default XML /// representation. /// </summary> public static Error DecodeString(string xml) { using (var sr = new StringReader(xml)) using (var reader = XmlReader.Create(sr)) { if (!reader.IsStartElement("error")) throw new ApplicationException("The error XML is not in the expected format."); return Decode(reader); } } /// <summary> /// Decodes an <see cref="Error"/> object from its XML representation. /// </summary> public static Error Decode(XmlReader reader) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.IsStartElement()) throw new ArgumentException("Reader is not positioned at the start of an element.", "reader"); // // Read out the attributes that contain the simple // typed state. // var error = new Error(); ReadXmlAttributes(reader, error); // // Move past the element. If it's not empty, then // read also the inner XML that contains complex // types like collections. // var isEmpty = reader.IsEmptyElement; reader.Read(); if (!isEmpty) { ReadInnerXml(reader, error); while (reader.NodeType != XmlNodeType.EndElement) reader.Skip(); reader.ReadEndElement(); } return error; } /// <summary> /// Reads the error data in XML attributes. /// </summary> private static void ReadXmlAttributes(XmlReader reader, Error error) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.IsStartElement()) throw new ArgumentException("Reader is not positioned at the start of an element.", "reader"); error.ApplicationName = reader.GetAttribute("application"); error.HostName = reader.GetAttribute("host"); error.Type = reader.GetAttribute("type"); error.Message = reader.GetAttribute("message"); error.Source = reader.GetAttribute("source"); error.Detail = reader.GetAttribute("detail"); error.User = reader.GetAttribute("user"); var timeString = reader.GetAttribute("time") ?? string.Empty; error.Time = timeString.Length == 0 ? new DateTime() : XmlConvert.ToDateTime(timeString); var statusCodeString = reader.GetAttribute("statusCode") ?? string.Empty; error.StatusCode = statusCodeString.Length == 0 ? 0 : XmlConvert.ToInt32(statusCodeString); error.WebHostHtmlMessage = reader.GetAttribute("webHostHtmlMessage"); } /// <summary> /// Reads the error data in child nodes. /// </summary> private static void ReadInnerXml(XmlReader reader, Error error) { if (reader == null) throw new ArgumentNullException("reader"); // // Loop through the elements, reading those that we // recognize. If an unknown element is found then // this method bails out immediately without // consuming it, assuming that it belongs to a subclass. // while (reader.IsStartElement()) { // // Optimization Note: This block could be re-wired slightly // to be more efficient by not causing a collection to be // created if the element is going to be empty. // NameValueCollection collection; switch (reader.Name) { case "serverVariables" : collection = error.ServerVariables; break; case "queryString" : collection = error.QueryString; break; case "form" : collection = error.Form; break; case "cookies" : collection = error.Cookies; break; case "additionalData" : collection = error.AdditionalData; break; default : reader.Skip(); continue; } if (reader.IsEmptyElement) reader.Read(); else UpcodeTo(reader, collection); } } /// <summary> /// Encodes the default XML representation of an <see cref="Error"/> /// object to a string. /// </summary> public static string EncodeString(Error error) { var sw = new StringWriter(); using (var writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, NewLineOnAttributes = true, CheckCharacters = false, OmitXmlDeclaration = true, // see issue #120: http://code.google.com/p/elmah/issues/detail?id=120 })) { writer.WriteStartElement("error"); Encode(error, writer); writer.WriteEndElement(); writer.Flush(); } return sw.ToString(); } /// <summary> /// Encodes the XML representation of an <see cref="Error"/> object. /// </summary> public static void Encode(Error error, XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (writer.WriteState != WriteState.Element) throw new ArgumentException("Writer is not in the expected Element state.", "writer"); // // Write out the basic typed information in attributes // followed by collections as inner elements. // WriteXmlAttributes(error, writer); WriteInnerXml(error, writer); } /// <summary> /// Writes the error data that belongs in XML attributes. /// </summary> private static void WriteXmlAttributes(Error error, XmlWriter writer) { Debug.Assert(error != null); if (writer == null) throw new ArgumentNullException("writer"); WriteXmlAttribute(writer, "application", error.ApplicationName); WriteXmlAttribute(writer, "host", error.HostName); WriteXmlAttribute(writer, "type", error.Type); WriteXmlAttribute(writer, "message", error.Message); WriteXmlAttribute(writer, "source", error.Source); WriteXmlAttribute(writer, "detail", error.Detail); WriteXmlAttribute(writer, "user", error.User); if (error.Time != DateTime.MinValue) WriteXmlAttribute(writer, "time", XmlConvert.ToString(error.Time.ToUniversalTime(), @"yyyy-MM-dd\THH:mm:ss.fffffff\Z")); if (error.StatusCode != 0) WriteXmlAttribute(writer, "statusCode", XmlConvert.ToString(error.StatusCode)); WriteXmlAttribute(writer, "webHostHtmlMessage", error.WebHostHtmlMessage); } /// <summary> /// Writes the error data that belongs in child nodes. /// </summary> private static void WriteInnerXml(Error error, XmlWriter writer) { Debug.Assert(error != null); if (writer == null) throw new ArgumentNullException("writer"); WriteCollection(writer, "serverVariables", error.ServerVariables); WriteCollection(writer, "queryString", error.QueryString); WriteCollection(writer, "form", error.Form); WriteCollection(writer, "cookies", error.Cookies); WriteCollection(writer, "additionalData", error.AdditionalData); } private static void WriteCollection(XmlWriter writer, string name, NameValueCollection collection) { Debug.Assert(writer != null); Debug.AssertStringNotEmpty(name); if (collection == null || collection.Count == 0) return; writer.WriteStartElement(name); Encode(collection, writer); writer.WriteEndElement(); } private static void WriteXmlAttribute(XmlWriter writer, string name, string value) { Debug.Assert(writer != null); Debug.AssertStringNotEmpty(name); if (!string.IsNullOrEmpty(value)) writer.WriteAttributeString(name, value); } /// <summary> /// Encodes an XML representation for a /// <see cref="NameValueCollection" /> object. /// </summary> private static void Encode(NameValueCollection collection, XmlWriter writer) { if (collection == null) throw new ArgumentNullException("collection"); if (writer == null) throw new ArgumentNullException("writer"); if (collection.Count == 0) return; // // Write out a named multi-value collection as follows // (example here is the ServerVariables collection): // // <item name="HTTP_URL"> // <value string="/myapp/somewhere/page.aspx" /> // </item> // <item name="QUERY_STRING"> // <value string="a=1&amp;b=2" /> // </item> // ... // foreach (string key in collection.Keys) { writer.WriteStartElement("item"); writer.WriteAttributeString("name", key); var values = collection.GetValues(key); if (values != null) { foreach (var value in values) { writer.WriteStartElement("value"); writer.WriteAttributeString("string", value); writer.WriteEndElement(); } } writer.WriteEndElement(); } } /// <summary> /// Updates an existing <see cref="NameValueCollection" /> object from /// its XML representation. /// </summary> private static void UpcodeTo(XmlReader reader, NameValueCollection collection) { if (reader == null) throw new ArgumentNullException("reader"); if (collection == null) throw new ArgumentNullException("collection"); Debug.Assert(!reader.IsEmptyElement); reader.Read(); // // Add entries into the collection as <item> elements // with child <value> elements are found. // while (reader.NodeType != XmlNodeType.EndElement) { if (reader.IsStartElement("item")) { string name = reader.GetAttribute("name"); bool isNull = reader.IsEmptyElement; reader.Read(); // <item> if (!isNull) { while (reader.NodeType != XmlNodeType.EndElement) { if (reader.IsStartElement("value")) // <value ...> { string value = reader.GetAttribute("string"); collection.Add(name, value); if (reader.IsEmptyElement) { reader.Read(); } else { reader.Read(); while (reader.NodeType != XmlNodeType.EndElement) reader.Skip(); reader.ReadEndElement(); } } else { reader.Skip(); } reader.MoveToContent(); } reader.ReadEndElement(); // </item> } else { collection.Add(name, null); } } else { reader.Skip(); } reader.MoveToContent(); } reader.ReadEndElement(); } } }
/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Shield { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; using HtmlAgilityPack; using Newtonsoft.Json.Linq; using Shield.Core; using Windows.Data.Xml.Dom; using XmlDocument = Windows.Data.Xml.Dom.XmlDocument; using XmlNodeList = Windows.Data.Xml.Dom.XmlNodeList; public class Parser { private XmlDocument doc; private string keypart; private string valuepart; private XmlNodeList nodes; public string Content { get; set; } public string Instructions { get; set; } public Dictionary<string, string> Dictionary { get; } = new Dictionary<string, string>(); public bool IsDictionary { get; set; } public string Tablename { get; set; } public string Result { get; set; } public bool Parse() { var temp = this.Content; var results = new List<string>(); var potentialResults = new Stack<string>(); var prefix = string.Empty; var parses = this.Instructions.Split('|'); foreach (var parse in parses) { var colon = parse.IndexOf(':'); if (colon > -1) { var cmd = parse.Substring(0, colon); var part = parse.Substring(colon + 1); var save = cmd.Contains("?"); var nextToken = cmd.Contains("&"); var prefixed = cmd.Contains("+"); var restore = cmd.Contains("^"); if (nextToken) { results.Add(temp); temp = string.Empty; } if (prefixed) { prefix += temp; temp = string.Empty; } if (restore) { temp = potentialResults.Count > 0 ? potentialResults.Pop() : this.Content; } if (save) { potentialResults.Push(prefix + temp); prefix = string.Empty; } var contains = temp.Contains(part); if (cmd.Contains("i")) { if (!this.CheckDoc(temp)) { return false; } this.nodes = this.doc.SelectNodes(part); this.IsDictionary = true; } else if (cmd.Contains("k")) { this.keypart = part; } else if (cmd.Contains("v")) { this.valuepart = part; } else if (cmd.Contains("table") && this.nodes != null) { if (part.Contains("name=")) { this.Tablename = part.Substring(part.IndexOf("name=") + 5); var j = this.Tablename.IndexOf(";"); if (j > -1) { this.Tablename = this.Tablename.Substring(0, j); } } foreach (var node in this.nodes) { IXmlNode key = null; XmlNodeList valueset = null; try { key = node.SelectSingleNode(this.keypart); valueset = node.SelectNodes(this.valuepart); } catch (Exception) { // skip if not matching continue; } if (!string.IsNullOrWhiteSpace(key?.InnerText)) { if (!string.IsNullOrWhiteSpace(key.InnerText) && !this.Dictionary.ContainsKey(key.InnerText)) { var values = new StringBuilder(); var count = valueset.Count(); foreach (var value in valueset) { values.Append(value.InnerText); if (--count > 0) { values.Append("~"); } } this.Dictionary.Add(key.InnerText, values.ToString()); } } } Debug.WriteLine("Table {0} saved count = {1}", this.Tablename, this.Dictionary.Count); } else if (cmd.Contains("R")) { temp = temp.RightOf(part); } else if (cmd.Contains("L")) { temp = temp.LeftOf(part); } else if (cmd.Contains("B")) { temp = temp.Between(part); } else if (cmd.Contains("!")) { temp = part; } else if (cmd.Contains("J") || cmd.Contains("j")) { var jParsed = JToken.Parse(temp); if (jParsed != null) { var jToken = jParsed.SelectToken(part); if (jToken != null) { if (cmd.Contains("j")) { temp = ((JProperty)jToken).Name; if (cmd.Contains("J")) { temp += ":'" + jToken.Value<string>() + "'"; } } else { temp = jToken.Value<string>(); } } else { temp = string.Empty; } } else { temp = string.Empty; } } else if (cmd.Contains("X")) { var expr = new Regex(part); var matches = expr.Match(part); var matchResults = new StringBuilder(); while (matches.Success) { contains = true; matchResults.Append(matches.Value); matchResults.Append("~"); matches = matches.NextMatch(); } temp = matchResults.ToString(); if (!string.IsNullOrWhiteSpace(temp)) { temp = temp.Substring(0, temp.Length - 1); } } else if (cmd.Contains("F")) { results.Add(prefix + temp); prefix = string.Empty; temp = string.Format(part, results.ToArray()); results.Clear(); } if (save && !contains) { temp = potentialResults.Pop(); } } if (string.IsNullOrWhiteSpace(temp)) { break; } } if (!string.IsNullOrWhiteSpace(temp)) { results.Add(prefix + temp); prefix = string.Empty; } var builder = new StringBuilder(); for (var i = 0; i < results.Count; i++) { builder.Append(results[i]); if (i < results.Count - 1) { builder.Append("|"); } } this.Result = builder.Length == 0 ? string.Empty : builder.ToString(); return true; } public bool CheckDoc(string temp) { if (this.doc != null) { return true; } try { this.doc = new XmlDocument(); this.doc.LoadXml(temp); } catch (Exception) { // backup leverage html agility pack try { var hdoc = new HtmlDocument(); hdoc.LoadHtml(temp); hdoc.OptionOutputAsXml = true; hdoc.OptionAutoCloseOnEnd = true; var stream = new MemoryStream(); var xtw = XmlWriter.Create( stream, new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment }); hdoc.Save(xtw); stream.Position = 0; this.doc.LoadXml((new StreamReader(stream)).ReadToEnd()); } catch (Exception) { return false; } } return true; } } }
using FluentAssertions; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace Nest.Tests.Unit.QueryParsers.Filter { [TestFixture] public class GeoShapeFilterTests : ParseFilterTestsBase { [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeEnvelope_Deserializes(string cacheName, string cacheKey, bool cache) { var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeEnvelope(p => p.Origin, d => d .Coordinates(new[] { new[] { 13.0, 53.0 }, new[] { 14.0, 52.0 } }) ) ); var filter = geoBaseShapeFilter as IGeoShapeEnvelopeFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("envelope"); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeCircle_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { -45.0, 45.0 }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeCircle(p => p.Origin, d => d .Coordinates(coordinates) .Radius("100m") ) ); var filter = geoBaseShapeFilter as IGeoShapeCircleFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("circle"); filter.Shape.Radius.Should().Be("100m"); filter.Shape.Coordinates.Should().BeEquivalentTo(coordinates); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeLineString_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { new[] { 13.0, 53.0 }, new[] { 14.0, 52.0 } }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeLineString(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapeLineStringFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("linestring"); filter.Shape.Coordinates.SelectMany(c => c).Should() .BeEquivalentTo(coordinates.SelectMany(c => c)); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeMultiLineString_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { new[] { new[] { 102.0, 2.0 }, new[] { 103.0, 2.0 }, new[] { 103.0, 3.0 }, new[] { 102.0, 3.0 } }, new[] { new[] { 100.0, 0.0 }, new[] { 101.0, 0.0 }, new[] { 101.0, 1.0 }, new[] { 100.0, 1.0 } }, new[] { new[] { 100.2, 0.2 }, new[] { 100.8, 0.2 }, new[] { 100.8, 0.8 }, new[] { 100.2, 0.8 } } }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeMultiLineString(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapeMultiLineStringFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("multilinestring"); filter.Shape.Coordinates.SelectMany(c => c.SelectMany(cc => cc)).Should() .BeEquivalentTo(coordinates.SelectMany(c => c.SelectMany(cc => cc))); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapePoint_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { 1.0, 2.0 }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapePoint(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapePointFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("point"); filter.Shape.Coordinates.Should().BeEquivalentTo(coordinates); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeMultiPoint_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { new[] { 13.0, 53.0 }, new[] { 14.0, 52.0 } }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeMultiPoint(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapeMultiPointFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("multipoint"); filter.Shape.Coordinates.SelectMany(c => c).Should() .BeEquivalentTo(coordinates.SelectMany(c => c)); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapePolygon_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { new[] { new[] { 100.0, 0.0 }, new[] { 101.0, 0.0 }, new[] { 101.0, 1.0 }, new[] { 100.0, 1.0 }, new [] { 100.0, 0.0 } }, new[] { new[] { 100.2, 0.2 }, new[] { 100.8, 0.2 }, new[] { 100.8, 0.8 }, new[] { 100.2, 0.8 }, new [] { 100.2, 0.2 } } }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapePolygon(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapePolygonFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("polygon"); filter.Shape.Coordinates.SelectMany(c => c.SelectMany(cc => cc)).Should() .BeEquivalentTo(coordinates.SelectMany(c => c.SelectMany(cc => cc))); } [Test] [TestCase("cacheName", "cacheKey", true)] public void GeoShapeMultiPolygon_Deserializes(string cacheName, string cacheKey, bool cache) { var coordinates = new[] { new [] { new [] { new [] { 102.0, 2.0 }, new [] { 103.0, 2.0 }, new [] { 103.0, 3.0 }, new [] { 102.0, 3.0 }, new [] { 102.0, 2.0 } } }, new [] { new [] { new [] { 100.0, 0.0 }, new [] { 101.0, 0.0 }, new [] { 101.0, 1.0 }, new [] {100.0, 1.0 }, new [] { 100.0, 0.0 } }, new [] { new [] { 100.2, 0.2 }, new [] { 100.8, 0.2 }, new [] { 100.8, 0.8 }, new [] { 100.2, 0.8 }, new [] { 100.2, 0.2 } } } }; var geoBaseShapeFilter = this.SerializeThenDeserialize(cacheName, cacheKey, cache, f => f.GeoShape, f => f.GeoShapeMultiPolygon(p => p.Origin, d => d .Coordinates(coordinates) ) ); var filter = geoBaseShapeFilter as IGeoShapeMultiPolygonFilter; filter.Should().NotBeNull(); filter.Field.Should().Be("origin"); filter.Should().NotBeNull(); filter.Shape.Should().NotBeNull(); filter.Shape.Type.Should().Be("multipolygon"); } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using PlayFab.Json.Utilities; using System.Collections; using System.Linq; namespace PlayFab.Json.Serialization { /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonArrayContract : JsonContainerContract { /// <summary> /// Gets the <see cref="Type"/> of the collection items. /// </summary> /// <value>The <see cref="Type"/> of the collection items.</value> public Type CollectionItemType { get; private set; } /// <summary> /// Gets a value indicating whether the collection type is a multidimensional array. /// </summary> /// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value> public bool IsMultidimensionalArray { get; private set; } private readonly bool _isCollectionItemTypeNullableType; private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private MethodCall<object, object> _genericWrapperCreator; private Func<object> _genericTemporaryCollectionCreator; internal bool IsArray { get; private set; } internal bool ShouldCreateWrapper { get; private set; } internal bool CanDeserialize { get; private set; } internal MethodBase ParametrizedConstructor { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; else CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); if (underlyingType == typeof(IList)) CreatedType = typeof(List<object>); if (CollectionItemType != null) ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType); IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = underlyingType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(CreatedType, CollectionItemType); IsReadOnlyOrFixedSize = true; canDeserialize = (ParametrizedConstructor != null); } //#endif else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType); if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = (ParametrizedConstructor != null); } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; if (CollectionItemType != null) _isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType); //#if !(NET20 || NET35 || NET40 || PORTABLE40) Type immutableCreatedType; MethodBase immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; ParametrizedConstructor = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } //#endif } internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); else constructorArgument = _genericCollectionDefinitionType; ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(null, list); } internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType); } return (IList)_genericTemporaryCollectionCreator(); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsSingle() { var test = new VectorAs__AsSingle(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsSingle { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector64<Single> value; value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector64<Single> value; value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<byte> byteResult = value.As<Single, byte>(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<double> doubleResult = value.As<Single, double>(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<short> shortResult = value.As<Single, short>(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<int> intResult = value.As<Single, int>(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<long> longResult = value.As<Single, long>(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<sbyte> sbyteResult = value.As<Single, sbyte>(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<float> floatResult = value.As<Single, float>(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<ushort> ushortResult = value.As<Single, ushort>(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<uint> uintResult = value.As<Single, uint>(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); Vector64<ulong> ulongResult = value.As<Single, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector64<Single> value; value = Vector64.Create(TestLibrary.Generator.GetSingle()); object byteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsByte)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<byte>)(byteResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object doubleResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsDouble)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<double>)(doubleResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object shortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt16)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<short>)(shortResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object intResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt32)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<int>)(intResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object longResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt64)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<long>)(longResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object sbyteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSByte)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<sbyte>)(sbyteResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object floatResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSingle)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<float>)(floatResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object ushortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt16)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ushort>)(ushortResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object uintResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt32)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<uint>)(uintResult), value); value = Vector64.Create(TestLibrary.Generator.GetSingle()); object ulongResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt64)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector64<T> result, Vector64<Single> value, [CallerMemberName] string method = "") where T : struct { Single[] resultElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result); Single[] valueElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Single[] resultElements, Single[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#if true using UnityEngine; using System.Collections.Generic; public enum MegaRopeType { Rope, Chain, Hose, Object, } // Do the editor scripts public enum MegaRopeSolverType { Euler, Verlet, } [AddComponentMenu("Procedural/Rope")] [ExecuteInEditMode, RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))] public class MegaRope : MonoBehaviour { public bool Rebuild = false; public MegaAxis axis = MegaAxis.Y; public Transform top; public Transform bottom; public LayerMask layer; public float fudge = 2.0f; public float boxsize = 0.1f; public float RopeLength; public bool fixedends = true; public float vel = 1.0f; public int drawsteps = 20; public bool DisplayDebug = true; public float radius = 1.0f; //public float ropeRadius = 0.1f; public MegaShape startShape; public Vector3 ropeup = Vector3.up; public bool DoCollide = false; public bool SelfCollide = false; public MegaRopeChainMesher chainMesher = new MegaRopeChainMesher(); public MegaRopeStrandedMesher strandedMesher = new MegaRopeStrandedMesher(); public MegaRopeHoseMesher hoseMesher = new MegaRopeHoseMesher(); public MegaRopeObjectMesher objectMesher = new MegaRopeObjectMesher(); public MegaRopeType type = MegaRopeType.Rope; // Non inspector params public List<MegaRopeMass> masses = new List<MegaRopeMass>(); public List<MegaRopeSpring> springs = new List<MegaRopeSpring>(); public List<MegaRopeConstraint> constraints = new List<MegaRopeConstraint>(); // Physics/Solver params public MegaRopeSolverType solverType = MegaRopeSolverType.Euler; public float spring = 1.0f; public float damp = 1.0f; public float timeStep = 0.01f; public float friction = 0.99f; public float Mass = 0.1f; public float Density = 1.0f; public float DampingRatio = 0.25f; // 1 being critically damped public Vector3 gravity = new Vector3(0.0f, -9.81f, 0.0f); public float airdrag = 0.02f; public float stiffspring = 1.0f; public float stiffdamp = 0.1f; public AnimationCurve stiffnessCrv = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1)); public float floorfriction = 0.9f; public float bounce = 1.0f; public int points = 10; public int iters = 4; Vector3 bsize = new Vector3(2.0f, 2.0f, 2.0f); Matrix4x4 wtm; Matrix4x4 mat = Matrix4x4.identity; PointConstraint1 endcon; Vector3[] masspos; MegaRopeSolver solver = new MegaRopeSolverDefault(); MegaRopeSolver verletsolver = new MegaRopeSolverVertlet(); public Mesh mesh = null; public bool stiffsprings = false; void InitFromShape(MegaShape shape) { float len = shape.splines[0].length; // adjust by and pre stretch //Debug.Log("Length " + len + "m"); float volume = len * 2.0f * Mathf.PI * radius; //Debug.Log("Volume " + volume + "m3"); float totalmass = Density * volume; // Option for fill or set count, or count per unit len *= 0.75f; int nummasses = (int)(len / radius) + 1; //Debug.Log("Num Masses " + nummasses); float m = totalmass / (float)nummasses; if ( DampingRatio > 1.0f ) DampingRatio = 1.0f; damp = (DampingRatio * 0.45f) * (2.0f * Mathf.Sqrt(m * spring)); // The Max spring rate is based on m //float dmpratio = damp / (2.0f * Mathf.Sqrt(m * spring)); //Debug.Log("Current Damp Ratio " + dmpratio); //float dmp = DampingRatio * (2.0f * Mathf.Sqrt(m * spring)); //Debug.Log("TotalMass " + totalmass + "kg element mass " + m + "kg damp " + damp); // Mmm or should me move along iters by radius * 2 RopeLength = 0.0f; if ( masses == null ) masses = new List<MegaRopeMass>(); transform.position = Vector3.zero; masses.Clear(); //float ms = Mass / (float)(points + 1); float rlen = 0.0f; Vector3 lastpos = Vector3.zero; for ( int i = 0; i <= nummasses; i++ ) { float alpha = (float)i / (float)nummasses; //points; //Vector3 pos = shape.transform.localToWorldMatrix.MultiplyPoint(shape.InterpCurve3D(0, alpha, true)); Vector3 pos = shape.transform.TransformPoint(shape.InterpCurve3D(0, alpha, true)); if ( i != 0 ) { rlen += Vector3.Distance(lastpos, pos); lastpos = pos; } MegaRopeMass rm = new MegaRopeMass(m, pos); masses.Add(rm); } if ( springs == null ) springs = new List<MegaRopeSpring>(); springs.Clear(); if ( constraints == null ) constraints = new List<MegaRopeConstraint>(); constraints.Clear(); for ( int i = 0; i < masses.Count - 1; i++ ) { MegaRopeSpring spr = new MegaRopeSpring(i, i + 1, spring, damp, this); springs.Add(spr); //spr.restlen = (rlen / masses.Count); // * 1.1f; RopeLength += spr.restlen; LengthConstraint lcon = new LengthConstraint(i, i + 1, spr.restlen); constraints.Add(lcon); } if ( stiffsprings ) { int gap = 2; for ( int i = 0; i < masses.Count - gap; i++ ) { float alpha = (float)i / (float)masses.Count; // BUG: For a curve shape, len for stuff springs should be sum of springs we span MegaRopeSpring spr = new MegaRopeSpring(i, i + gap, stiffspring * stiffnessCrv.Evaluate(alpha), stiffdamp * stiffnessCrv.Evaluate(alpha), this); //spr.restlen = (springs[i].restlen + springs[i + 1].restlen); // * 1.1f; //spr.restlen = (RopeLength / masses.Count) * 2.0f; //(springs[i].restlen + springs[i + gap].restlen) * 1.0f; // TODO: Add these for rope, not needed for chain springs.Add(spr); LengthConstraint lcon = new LengthConstraint(i, i + gap, spr.restlen); //(RopeLength / masses.Count) * 2.0f); //spr.restlen); constraints.Add(lcon); } } if ( top ) { top.position = masses[0].pos; float ln = (masses[0].pos - masses[1].pos).magnitude; NewPointConstraint pconn = new NewPointConstraint(0, 1, ln, top.transform); //PointConstraint pconn = new PointConstraint(0, top.transform); constraints.Add(pconn); } if ( bottom ) { bottom.position = masses[masses.Count - 1].pos; float ln = (masses[masses.Count - 1].pos - masses[masses.Count - 2].pos).magnitude; NewPointConstraint pconn = new NewPointConstraint(masses.Count - 1, masses.Count - 2, ln, bottom.transform); //PointConstraint pconn = new PointConstraint(masses.Count - 1, bottom.transform); constraints.Add(pconn); } // Apply fixed end constraints //PointConstraint pcon = new PointConstraint(0, top.transform); //constraints.Add(pcon); //pcon = new PointConstraint(masses.Count - 1, bottom.transform); //constraints.Add(pcon); //float ln = (masses[0].pos - masses[1].pos).magnitude; //NewPointConstraint pconn = new NewPointConstraint(0, 1, ln, top.transform); //constraints.Add(pconn); //ln = (masses[masses.Count - 1].pos - masses[masses.Count - 2].pos).magnitude; //pconn = new NewPointConstraint(masses.Count - 1, masses.Count - 2, ln, bottom.transform); //constraints.Add(pconn); //ln = (masses[masses.Count - 1].pos - masses[masses.Count - 2].pos).magnitude; //NewPointConstraint pc = new NewPointConstraint(masses.Count / 2, (masses.Count / 2) + 1, ln, middle.transform); //constraints.Add(pc); if ( top ) { PointConstraint1 pcon1 = new PointConstraint1(); pcon1.p1 = 1; pcon1.off = new Vector3(0.0f, springs[0].restlen, 0.0f); pcon1.obj = top.transform; //.position; //constraints.Add(pcon1); //endcon = pcon1; } masspos = new Vector3[masses.Count + 2]; for ( int i = 0; i < masses.Count; i++ ) masspos[i + 1] = masses[i].pos; masspos[0] = masspos[1]; masspos[masspos.Length - 1] = masspos[masspos.Length - 2]; } public void Init() { if ( startShape != null ) InitFromShape(startShape); else { if ( top == null || bottom == null ) return; Vector3 p1 = top.position; Vector3 p2 = bottom.position; RopeLength = (p1 - p2).magnitude; if ( masses == null ) masses = new List<MegaRopeMass>(); transform.position = Vector3.zero; masses.Clear(); float ms = Mass / (float)(points + 1); for ( int i = 0; i <= points; i++ ) { float alpha = (float)i / (float)points; MegaRopeMass rm = new MegaRopeMass(ms, Vector3.Lerp(p1, p2, alpha)); masses.Add(rm); } if ( springs == null ) springs = new List<MegaRopeSpring>(); springs.Clear(); if ( constraints == null ) constraints = new List<MegaRopeConstraint>(); constraints.Clear(); for ( int i = 0; i < masses.Count - 1; i++ ) { MegaRopeSpring spr = new MegaRopeSpring(i, i + 1, spring, damp, this); springs.Add(spr); LengthConstraint lcon = new LengthConstraint(i, i + 1, spr.restlen); constraints.Add(lcon); } int gap = 2; for ( int i = 0; i < masses.Count - gap; i++ ) { float alpha = (float)i / (float)masses.Count; MegaRopeSpring spr = new MegaRopeSpring(i, i + gap, stiffspring * stiffnessCrv.Evaluate(alpha), stiffdamp * stiffnessCrv.Evaluate(alpha), this); springs.Add(spr); LengthConstraint lcon = new LengthConstraint(i, i + gap, spr.restlen); constraints.Add(lcon); } // Apply fixed end constraints PointConstraint pcon = new PointConstraint(0, top.transform); constraints.Add(pcon); pcon = new PointConstraint(masses.Count - 1, bottom.transform); constraints.Add(pcon); PointConstraint1 pcon1 = new PointConstraint1(); pcon1.p1 = 1; pcon1.off = new Vector3(0.0f, springs[0].restlen, 0.0f); pcon1.obj = top.transform; //.position; constraints.Add(pcon1); endcon = pcon1; masspos = new Vector3[masses.Count + 2]; for ( int i = 0; i < masses.Count; i++ ) masspos[i + 1] = masses[i].pos; masspos[0] = masspos[1]; masspos[masspos.Length - 1] = masspos[masspos.Length - 2]; } } void RopeUpdate(float t) { float time = Time.deltaTime * fudge; if ( time > 0.05f ) time = 0.05f; //time = 0.01f; switch ( solverType ) { case MegaRopeSolverType.Euler: while ( time > 0.0f ) { time -= timeStep; solver.doIntegration1(this, timeStep); } break; case MegaRopeSolverType.Verlet: while ( time > 0.0f ) { time -= timeStep; verletsolver.doIntegration1(this, timeStep); } break; } //while ( time > 0.0f ) //{ // time -= timeStep; // solver.doIntegration1(this, timeStep); //} Collide(); } void Start() { Init(); } [ContextMenu("Rebuild Rope")] public void RebuildRope() { Init(); } // fixedends is a constraint, need to add as one void LateUpdate() { if ( Rebuild ) { Rebuild = false; Init(); } // TODO: Have a Valid flag for this if ( masses == null || masses.Count == 0 || masspos == null || masspos.Length == 0 ) return; if ( endcon != null ) endcon.active = fixedends; RopeUpdate(timeStep); for ( int i = 0; i < masses.Count; i++ ) masspos[i + 1] = masses[i].pos; masspos[0] = masses[0].pos - (masses[1].pos - masses[0].pos); masspos[masspos.Length - 1] = masses[masses.Count - 1].pos + (masses[masses.Count - 1].pos - masses[masses.Count - 2].pos); #if true //if ( mesh == null ) //{ // Debug.Log("No mesh"); // mesh = MegaUtils.GetMesh(gameObject); // if ( mesh == null ) // { // Debug.Log("new mesh"); // mesh = new Mesh(); // } //} if ( mesh == null ) { Debug.Log("No mesh"); MeshFilter mf = gameObject.GetComponent<MeshFilter>(); if ( mf == null ) mf = gameObject.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh(); MeshRenderer mr = gameObject.GetComponent<MeshRenderer>(); if ( mr == null ) { mr = gameObject.AddComponent<MeshRenderer>(); } Material[] mats = new Material[1]; mr.sharedMaterials = mats; mesh = mf.sharedMesh; //Utils.GetMesh(gameObject); mesh.name = "Rope Mesh"; } switch ( type ) { case MegaRopeType.Rope: strandedMesher.BuildMesh(this); break; case MegaRopeType.Chain: chainMesher.BuildMesh(this); break; case MegaRopeType.Hose: hoseMesher.BuildMesh(this); break; case MegaRopeType.Object: objectMesher.BuildMesh(this); break; } //float currentlength = 0.0f; //for ( int i = 0; i < masses.Count; i++ ) //{ // currentlength += springs[i].len; //} //Debug.Log("Current len " + currentlength + " length " + RopeLength); if ( top ) { Rigidbody rbody = top.GetComponent<Rigidbody>(); if ( rbody ) { //float force = (springs[0].len - springs[0].restlen) * rbodyforce; //float force = (currentlength - RopeLength) * rbodyforce; //Vector3 dir = (masses[springs[0].p2].pos - masses[springs[0].p1].pos).normalized; //rbody.AddForce(dir * force); } } if ( bottom ) { Rigidbody rbody = bottom.GetComponent<Rigidbody>(); if ( rbody ) { float force = (springs[springs.Count - 1].len - springs[springs.Count - 1].restlen) * rbodyforce; //float force = (currentlength - RopeLength) * rbodyforce; //Vector3 dir = (bottom.position - masses[masses.Count - 1].pos).normalized; //float force = dir.magnitude * rbodyforce; //bottom.position - masses[masses.Count - 1].pos if ( force > 0.0f ) { Vector3 dir = (masses[springs[springs.Count - 1].p1].pos - masses[springs[springs.Count - 1].p2].pos).normalized; rbody.AddForce(dir * force); } } } #endif } public float rbodyforce = 10.0f; public void OnDrawGizmos() { Display(); } // Mmm should be in gizmo code void Display() { if ( masses != null && masses.Count != 0 && masspos != null && masspos.Length != 0 ) { if ( DisplayDebug ) { DrawSpline(drawsteps, vel * 0.0f); Color col = Color.green; col.a = 0.5f; Gizmos.color = col; for ( int i = 0; i < masses.Count; i++ ) Gizmos.DrawSphere(masses[i].pos, radius); //bsize * boxsize); // Should be spheres Vector3[] verts = mesh.vertices; for ( int i = 0; i < verts.Length; i++ ) { //Gizmos.DrawCube(verts[i], bsize * boxsize * 0.1f); // Should be spheres } if ( type == MegaRopeType.Rope ) { Vector3 last = Vector3.zero; for ( int i = 18; i < verts.Length; i += 9 ) { //for ( int j = 0; j < 9; j++ ) { //switch ( j ) //{ //case 0: Gizmos.color = Color.red; //break; //case 8: // Gizmos.color = Color.green; // break; //default: // Gizmos.color = Color.blue; // break; //} if ( i > 18 ) { Gizmos.DrawLine(verts[i], last); } Gizmos.DrawCube(verts[i], bsize * boxsize * 0.1f); // Should be spheres last = verts[i]; } } } } } } // Spline interp etc public Vector3 Interp1(float t) { int numSections = masses.Count - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float)numSections), numSections - 1); float u = t * (float)numSections - (float)currPt; Vector3 a = masses[currPt].pos; Vector3 b = masses[currPt + 1].pos; Vector3 c = masses[currPt + 2].pos; Vector3 d = masses[currPt + 3].pos; return 0.5f * ((-a + 3f * b - 3f * c + d) * (u * u * u) + (2f * a - 5f * b + 4f * c - d) * (u * u) + (-a + c) * u + 2f * b); } public Vector3 Velocity1(float t) { int numSections = masses.Count - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float)numSections), numSections - 1); float u = t * (float)numSections - (float)currPt; Vector3 a = masses[currPt].pos; Vector3 b = masses[currPt + 1].pos; Vector3 c = masses[currPt + 2].pos; Vector3 d = masses[currPt + 3].pos; return 1.5f * (-a + 3f * b - 3f * c + d) * (u * u) + (2f * a - 5f * b + 4f * c - d) * u + .5f * c - .5f * a; } // Better way is to just plop sentry masses and mark as non update but plop constraint on to be sentries public Vector3 Interp(float t) { //Debug.Log("t " + t); int numSections = masspos.Length - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float)numSections), numSections - 1); float u = t * (float)numSections - (float)currPt; //Debug.Log("currPt " + currPt + " masses " + masses.Count); Vector3 a = masspos[currPt]; Vector3 b = masspos[currPt + 1]; Vector3 c = masspos[currPt + 2]; Vector3 d = masspos[currPt + 3]; return 0.5f * ((-a + 3f * b - 3f * c + d) * (u * u * u) + (2f * a - 5f * b + 4f * c - d) * (u * u) + (-a + c) * u + 2f * b); } public Vector3 Velocity(float t) { int numSections = masspos.Length - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float)numSections), numSections - 1); float u = t * (float)numSections - (float)currPt; Vector3 a = masspos[currPt]; Vector3 b = masspos[currPt + 1]; Vector3 c = masspos[currPt + 2]; Vector3 d = masspos[currPt + 3]; return 1.5f * (-a + 3f * b - 3f * c + d) * (u * u) + (2f * a - 5f * b + 4f * c - d) * u + .5f * c - .5f * a; } void DrawSpline(int steps, float t) { if ( masses != null && masses.Count != 0 && masspos != null && masspos.Length != 0 ) { //Gizmos.color = Color.white; Vector3 prevPt = Interp(0); for ( int i = 1; i <= steps; i++ ) { if ( (i & 1) == 1 ) Gizmos.color = Color.white; else Gizmos.color = Color.black; float pm = (float)i / (float)steps; Vector3 currPt = Interp(pm); Gizmos.DrawLine(currPt, prevPt); prevPt = currPt; } Gizmos.color = Color.blue; Vector3 pos = Interp(t); Gizmos.DrawLine(pos, pos + Velocity(t)); } } // We keep track of last cross section first vert, or actually do a transform of up vector // then with new lookat we find up again, find the rotation to line up new up with last up public Matrix4x4 GetDeformMat(float percent) { float alpha = percent; Vector3 ps = Interp(alpha); Vector3 ps1 = ps + Velocity(alpha); Vector3 relativePos = ps1 - ps; // This is Vel? Quaternion rotation = Quaternion.LookRotation(relativePos, ropeup); //vertices[p + 1].point - vertices[p].point); wtm.SetTRS(ps, rotation, Vector3.one); wtm = mat * wtm; // * roll; return wtm; } public Matrix4x4 CalcFrame(Vector3 T, ref Vector3 N, ref Vector3 B) { Matrix4x4 mat = Matrix4x4.identity; //Tn+1 = T(sn+1) N = Vector3.Cross(B, T).normalized; B = Vector3.Cross(T, N).normalized; //mat.SetRow(0, T); //mat.SetRow(1, N); //mat.SetRow(2, B); //mat.SetRow(2, T); //mat.SetRow(0, N); //mat.SetRow(1, B); //mat.SetRow(1, T); //mat.SetRow(2, N); //mat.SetRow(0, B); //mat.SetRow(0, T); //mat.SetRow(2, N); //mat.SetRow(1, B); //mat.SetRow(1, T); //mat.SetRow(0, N); //mat.SetRow(2, B); //mat.SetRow(2, T); //mat.SetRow(1, N); //mat.SetRow(0, B); //mat.SetColumn(0, T); //mat.SetColumn(1, N); //mat.SetColumn(2, B); //mat.SetColumn(0, T); //mat.SetColumn(2, N); //mat.SetColumn(1, B); //mat.SetColumn(1, T); //mat.SetColumn(2, N); //mat.SetColumn(0, B); //mat.SetColumn(1, T); //mat.SetColumn(0, N); //mat.SetColumn(2, B); mat.SetColumn(2, T); mat.SetColumn(0, N); mat.SetColumn(1, B); //mat.SetColumn(2, T); //mat.SetColumn(1, N); //mat.SetColumn(0, B); return mat; } public Matrix4x4 GetDeformMat(float percent, Vector3 up) { float alpha = percent; Vector3 ps = Interp(alpha); Vector3 ps1 = ps + Velocity(alpha); Vector3 relativePos = ps1 - ps; // This is Vel? Quaternion rotation = Quaternion.LookRotation(relativePos, up); //vertices[p + 1].point - vertices[p].point); wtm.SetTRS(ps, rotation, Vector3.one); wtm = mat * wtm; // * roll; return wtm; } Matrix4x4 GetLinkMat(float alpha, float last) { Vector3 ps = Interp(last); Vector3 ps1 = Interp(alpha); //ps + Velocity(alpha); Vector3 relativePos = ps1 - ps; // This is Vel? Quaternion rotation = Quaternion.LookRotation(relativePos, ropeup); //vertices[p + 1].point - vertices[p].point); wtm.SetTRS(ps, rotation, Vector3.one); wtm = mat * wtm; // * roll; return wtm; } Quaternion GetLinkQuat(float alpha, float last, out Vector3 ps) { ps = Interp(last); Vector3 ps1 = Interp(alpha); //ps + Velocity(alpha); Vector3 relativePos = ps1 - ps; // This is Vel? return Quaternion.LookRotation(relativePos, ropeup); //vertices[p + 1].point - vertices[p].point); } void Collide() { if ( DoCollide ) { int count = masses.Count - 1; for ( int i = 0; i < count; i++ ) { for ( int s = i + 2; s < count; s++ ) { //float dist = MegaRopeSpring.GetDist(this, springs[i], springs[s]); //if ( dist < ropeRadius ) { //Debug.Log("Spring " + i + " collides with " + s + " " + dist); } } } } } } #endif
// Copyright (c) 2012, Event Store LLP // 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 the Event Store LLP 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. // using System; using System.Diagnostics; using EventStore.Common.Log; using EventStore.Core.Bus; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public class EventProcessingProjectionProcessingPhase : EventSubscriptionBasedProjectionProcessingPhase, IHandle<EventReaderSubscriptionMessage.CommittedEventReceived>, IHandle<EventReaderSubscriptionMessage.PartitionEofReached>, IEventProcessingProjectionPhase { private readonly IProjectionStateHandler _projectionStateHandler; private readonly bool _definesStateTransform; private readonly StatePartitionSelector _statePartitionSelector; private readonly bool _isBiState; private string _handlerPartition; //private bool _sharedStateSet; private readonly Stopwatch _stopwatch; public EventProcessingProjectionProcessingPhase( CoreProjection coreProjection, Guid projectionCorrelationId, IPublisher publisher, ProjectionConfig projectionConfig, Action updateStatistics, IProjectionStateHandler projectionStateHandler, PartitionStateCache partitionStateCache, bool definesStateTransform, string projectionName, ILogger logger, CheckpointTag zeroCheckpointTag, ICoreProjectionCheckpointManager coreProjectionCheckpointManager, StatePartitionSelector statePartitionSelector, ReaderSubscriptionDispatcher subscriptionDispatcher, IReaderStrategy readerStrategy, IResultWriter resultWriter, bool useCheckpoints, bool stopOnEof, bool isBiState, bool orderedPartitionProcessing) : base( publisher, coreProjection, projectionCorrelationId, coreProjectionCheckpointManager, projectionConfig, projectionName, logger, zeroCheckpointTag, partitionStateCache, resultWriter, updateStatistics, subscriptionDispatcher, readerStrategy, useCheckpoints, stopOnEof, orderedPartitionProcessing, isBiState) { _projectionStateHandler = projectionStateHandler; _definesStateTransform = definesStateTransform; _statePartitionSelector = statePartitionSelector; _isBiState = isBiState; _stopwatch = new Stopwatch(); } public void Handle(EventReaderSubscriptionMessage.CommittedEventReceived message) { //TODO: make sure this is no longer required : if (_state != State.StateLoaded) if (IsOutOfOrderSubscriptionMessage(message)) return; RegisterSubscriptionMessage(message); try { CheckpointTag eventTag = message.CheckpointTag; var committedEventWorkItem = new CommittedEventWorkItem(this, message, _statePartitionSelector); _processingQueue.EnqueueTask(committedEventWorkItem, eventTag); if (_state == PhaseState.Running) // prevent processing mostly one projection EnsureTickPending(); } catch (Exception ex) { _coreProjection.SetFaulted(ex); } } public void Handle(EventReaderSubscriptionMessage.PartitionEofReached message) { if (IsOutOfOrderSubscriptionMessage(message)) return; RegisterSubscriptionMessage(message); try { var partitionCompletedWorkItem = new PartitionCompletedWorkItem( this, _checkpointManager, message.Partition, message.CheckpointTag); _processingQueue.EnqueueTask( partitionCompletedWorkItem, message.CheckpointTag, allowCurrentPosition: true); ProcessEvent(); } catch (Exception ex) { _coreProjection.SetFaulted(ex); } } public string TransformCatalogEvent(EventReaderSubscriptionMessage.CommittedEventReceived message) { switch (_state) { case PhaseState.Running: var result = InternalTransformCatalogEvent(message); return result; case PhaseState.Stopped: _logger.Error("Ignoring committed catalog event in stopped state"); return null; default: throw new NotSupportedException(); } } public EventProcessedResult ProcessCommittedEvent( EventReaderSubscriptionMessage.CommittedEventReceived message, string partition) { switch (_state) { case PhaseState.Running: var result = InternalProcessCommittedEvent(partition, message); return result; case PhaseState.Stopped: _logger.Error("Ignoring committed event in stopped state"); return null; default: throw new NotSupportedException(); } } private EventProcessedResult InternalProcessCommittedEvent( string partition, EventReaderSubscriptionMessage.CommittedEventReceived message) { string newState; string projectionResult; EmittedEventEnvelope[] emittedEvents; //TODO: support shared state string newSharedState; var hasBeenProcessed = SafeProcessEventByHandler( partition, message, out newState, out newSharedState, out projectionResult, out emittedEvents); if (hasBeenProcessed) { var newPartitionState = new PartitionState(newState, projectionResult, message.CheckpointTag); var newSharedPartitionState = newSharedState != null ? new PartitionState(newSharedState, null, message.CheckpointTag) : null; return InternalCommittedEventProcessed( partition, message, emittedEvents, newPartitionState, newSharedPartitionState); } return null; } private string InternalTransformCatalogEvent( EventReaderSubscriptionMessage.CommittedEventReceived message) { var result = SafeTransformCatalogEventByHandler(message); return result; } private bool SafeProcessEventByHandler( string partition, EventReaderSubscriptionMessage.CommittedEventReceived message, out string newState, out string newSharedState, out string projectionResult, out EmittedEventEnvelope[] emittedEvents) { projectionResult = null; //TODO: not emitting (optimized) projection handlers can skip serializing state on each processed event bool hasBeenProcessed; try { hasBeenProcessed = ProcessEventByHandler( partition, message, out newState, out newSharedState, out projectionResult, out emittedEvents); } catch (Exception ex) { // update progress to reflect exact fault position _checkpointManager.Progress(message.Progress); SetFaulting( String.Format( "The {0} projection failed to process an event.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}", _projectionName, GetHandlerTypeName(), message.CheckpointTag, ex.Message), ex); newState = null; newSharedState = null; emittedEvents = null; hasBeenProcessed = false; } newState = newState ?? ""; return hasBeenProcessed; } private string SafeTransformCatalogEventByHandler(EventReaderSubscriptionMessage.CommittedEventReceived message) { string result; try { result = TransformCatalogEventByHandler(message); } catch (Exception ex) { // update progress to reflect exact fault position _checkpointManager.Progress(message.Progress); SetFaulting( String.Format( "The {0} projection failed to transform a catalog event.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}", _projectionName, GetHandlerTypeName(), message.CheckpointTag, ex.Message), ex); result = null; } return result; } private string GetHandlerTypeName() { return _projectionStateHandler.GetType().Namespace + "." + _projectionStateHandler.GetType().Name; } private bool ProcessEventByHandler( string partition, EventReaderSubscriptionMessage.CommittedEventReceived message, out string newState, out string newSharedState, out string projectionResult, out EmittedEventEnvelope[] emittedEvents) { projectionResult = null; SetHandlerState(partition); _stopwatch.Start(); var result = _projectionStateHandler.ProcessEvent( partition, message.CheckpointTag, message.EventCategory, message.Data, out newState, out newSharedState, out emittedEvents); if (result) { var oldState = _partitionStateCache.GetLockedPartitionState(partition); //TODO: depending on query processing final state to result transformation should happen either here (if EOF) on while writing results if ( /*_producesRunningResults && */oldState.State != newState) { if (_definesStateTransform) { projectionResult = _projectionStateHandler.TransformStateToResult(); } else { projectionResult = newState; } } else { projectionResult = oldState.Result; } } _stopwatch.Stop(); return result; } private string TransformCatalogEventByHandler(EventReaderSubscriptionMessage.CommittedEventReceived message) { _stopwatch.Start(); var result = _projectionStateHandler.TransformCatalogEvent(message.CheckpointTag, message.Data); _stopwatch.Stop(); return result; } private void SetHandlerState(string partition) { if (_handlerPartition == partition) return; var newState = _partitionStateCache.GetLockedPartitionState(partition); _handlerPartition = partition; if (newState != null && !String.IsNullOrEmpty(newState.State)) _projectionStateHandler.Load(newState.State); else { _projectionStateHandler.Initialize(); } //if (!_sharedStateSet && _isBiState) if (_isBiState) { var newSharedState = _partitionStateCache.GetLockedPartitionState(""); if (newSharedState != null && !String.IsNullOrEmpty(newSharedState.State)) _projectionStateHandler.LoadShared(newSharedState.State); else _projectionStateHandler.InitializeShared(); } } public override void NewCheckpointStarted(CheckpointTag at) { var checkpointHandler = _projectionStateHandler as IProjectionCheckpointHandler; if (checkpointHandler != null) { EmittedEventEnvelope[] emittedEvents; try { checkpointHandler.ProcessNewCheckpoint(at, out emittedEvents); } catch (Exception ex) { var faultedReason = String.Format( "The {0} projection failed to process a checkpoint start.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}", _projectionName, GetHandlerTypeName(), at, ex.Message); SetFaulting(faultedReason, ex); emittedEvents = null; } if (emittedEvents != null && emittedEvents.Length > 0) { if (!ValidateEmittedEvents(emittedEvents)) return; if (_state == PhaseState.Running) _resultWriter.EventsEmitted(emittedEvents, Guid.Empty, correlationId: null); } } } public override void GetStatistics(ProjectionStatistics info) { base.GetStatistics(info); info.CoreProcessingTime = _stopwatch.ElapsedMilliseconds; } public override void Dispose() { if (_projectionStateHandler != null) _projectionStateHandler.Dispose(); } } }
using System; using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; namespace BTCPayServer.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20200110064617_OpenIddictUpdate")] public partial class OpenIddictUpdate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { if (!migrationBuilder.IsSqlite()) { migrationBuilder.AlterColumn<string>( name: "Subject", table: "OpenIddictTokens", maxLength: 450, nullable: true, oldClrType: typeof(string), oldMaxLength: 450); migrationBuilder.AlterColumn<string>( name: "Subject", table: "OpenIddictAuthorizations", maxLength: 450, nullable: true, oldClrType: typeof(string), oldMaxLength: 450); } else { ReplaceOldTable(migrationBuilder, s => { migrationBuilder.CreateTable( name: s, columns: table => new { ApplicationId = table.Column<string>(nullable: true, maxLength: null), AuthorizationId = table.Column<string>(nullable: true, maxLength: null), ConcurrencyToken = table.Column<string>(maxLength: 50, nullable: true), CreationDate = table.Column<DateTimeOffset>(nullable: true), ExpirationDate = table.Column<DateTimeOffset>(nullable: true), Id = table.Column<string>(nullable: false, maxLength: null), Payload = table.Column<string>(nullable: true), Properties = table.Column<string>(nullable: true), ReferenceId = table.Column<string>(maxLength: 100, nullable: true), Status = table.Column<string>(maxLength: 25, nullable: false), Subject = table.Column<string>(maxLength: 450, nullable: true), Type = table.Column<string>(maxLength: 25, nullable: false) }, constraints: table => { table.PrimaryKey("PK_OpenIddictTokens", x => x.Id); table.ForeignKey( name: "FK_OpenIddictTokens_OpenIddictApplications_ApplicationId", column: x => x.ApplicationId, principalTable: "OpenIddictApplications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_OpenIddictTokens_OpenIddictAuthorizations_AuthorizationId", column: x => x.AuthorizationId, principalTable: "OpenIddictAuthorizations", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); }, "OpenIddictTokens"); ReplaceOldTable(migrationBuilder, s => { migrationBuilder.CreateTable( name: s, columns: table => new { ApplicationId = table.Column<string>(nullable: true, maxLength: null), ConcurrencyToken = table.Column<string>(maxLength: 50, nullable: true), Id = table.Column<string>(nullable: false, maxLength: null), Properties = table.Column<string>(nullable: true), Scopes = table.Column<string>(nullable: true), Status = table.Column<string>(maxLength: 25, nullable: false), Subject = table.Column<string>(maxLength: 450, nullable: true), Type = table.Column<string>(maxLength: 25, nullable: false) }, constraints: table => { table.PrimaryKey("PK_OpenIddictAuthorizations", x => x.Id); table.ForeignKey( name: "FK_OpenIddictAuthorizations_OpenIddictApplications_ApplicationId", column: x => x.ApplicationId, principalTable: "OpenIddictApplications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); }, "OpenIddictAuthorizations"); } migrationBuilder.AddColumn<string>( name: "Requirements", table: "OpenIddictApplications", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { if (!migrationBuilder.IsSqlite()) { migrationBuilder.DropColumn( name: "Requirements", table: "OpenIddictApplications"); migrationBuilder.AlterColumn<string>( name: "Subject", table: "OpenIddictTokens", maxLength: 450, nullable: false, oldClrType: typeof(string), oldMaxLength: 450, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Subject", table: "OpenIddictAuthorizations", maxLength: 450, nullable: false, oldClrType: typeof(string), oldMaxLength: 450, oldNullable: true); } else { ReplaceOldTable(migrationBuilder, s => { migrationBuilder.CreateTable( name: s, columns: table => new { ApplicationId = table.Column<string>(nullable: true, maxLength: null), AuthorizationId = table.Column<string>(nullable: true, maxLength: null), ConcurrencyToken = table.Column<string>(maxLength: 50, nullable: true), CreationDate = table.Column<DateTimeOffset>(nullable: true), ExpirationDate = table.Column<DateTimeOffset>(nullable: true), Id = table.Column<string>(nullable: false, maxLength: null), Payload = table.Column<string>(nullable: true), Properties = table.Column<string>(nullable: true), ReferenceId = table.Column<string>(maxLength: 100, nullable: true), Status = table.Column<string>(maxLength: 25, nullable: false), Subject = table.Column<string>(maxLength: 450, nullable: false), Type = table.Column<string>(maxLength: 25, nullable: false) }, constraints: table => { table.PrimaryKey("PK_OpenIddictTokens", x => x.Id); table.ForeignKey( name: "FK_OpenIddictTokens_OpenIddictApplications_ApplicationId", column: x => x.ApplicationId, principalTable: "OpenIddictApplications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_OpenIddictTokens_OpenIddictAuthorizations_AuthorizationId", column: x => x.AuthorizationId, principalTable: "OpenIddictAuthorizations", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); }, "OpenIddictTokens", "WHERE Subject IS NOT NULL"); ReplaceOldTable(migrationBuilder, s => { migrationBuilder.CreateTable( name: s, columns: table => new { ApplicationId = table.Column<string>(nullable: true, maxLength: null), ConcurrencyToken = table.Column<string>(maxLength: 50, nullable: true), Id = table.Column<string>(nullable: false, maxLength: null), Properties = table.Column<string>(nullable: true), Scopes = table.Column<string>(nullable: true), Status = table.Column<string>(maxLength: 25, nullable: false), Subject = table.Column<string>(maxLength: 450, nullable: false), Type = table.Column<string>(maxLength: 25, nullable: false) }, constraints: table => { table.PrimaryKey("PK_OpenIddictAuthorizations", x => x.Id); table.ForeignKey( name: "FK_OpenIddictAuthorizations_OpenIddictApplications_ApplicationId", column: x => x.ApplicationId, principalTable: "OpenIddictApplications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); }, "OpenIddictAuthorizations", "WHERE Subject IS NOT NULL"); ReplaceOldTable(migrationBuilder, s => { migrationBuilder.CreateTable( name: s, columns: table => new { ClientId = table.Column<string>(maxLength: 100, nullable: false), ClientSecret = table.Column<string>(nullable: true), ConcurrencyToken = table.Column<string>(maxLength: 50, nullable: true), ConsentType = table.Column<string>(nullable: true), DisplayName = table.Column<string>(nullable: true), Id = table.Column<string>(nullable: false, maxLength: null), Permissions = table.Column<string>(nullable: true), PostLogoutRedirectUris = table.Column<string>(nullable: true), Properties = table.Column<string>(nullable: true), RedirectUris = table.Column<string>(nullable: true), Type = table.Column<string>(maxLength: 25, nullable: false), ApplicationUserId = table.Column<string>(nullable: true, maxLength: null) }, constraints: table => { table.PrimaryKey("PK_OpenIddictApplications", x => x.Id); table.ForeignKey( name: "FK_OpenIddictApplications_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); }, "OpenIddictApplications", "", "ClientId, ClientSecret, ConcurrencyToken, ConsentType, DisplayName, Id, Permissions, PostLogoutRedirectUris, Properties, RedirectUris, Type, ApplicationUserId"); } } private void ReplaceOldTable(MigrationBuilder migrationBuilder, Action<string> createTable, string tableName, string whereClause = "", string columns = "*") { createTable.Invoke($"New_{tableName}"); migrationBuilder.Sql( $"INSERT INTO New_{tableName} {(columns == "*" ? string.Empty : $"({columns})")}SELECT {columns} FROM {tableName} {whereClause};"); migrationBuilder.Sql("PRAGMA foreign_keys=\"0\"", true); migrationBuilder.Sql($"DROP TABLE {tableName}", true); migrationBuilder.Sql($"ALTER TABLE New_{tableName} RENAME TO {tableName}", true); migrationBuilder.Sql("PRAGMA foreign_keys=\"1\"", true); } } }
namespace KabMan.Forms { partial class NewCableModelForm { /// <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(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule2 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewCableModelForm)); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.AddPropertyButton = new DevExpress.XtraEditors.SimpleButton(); this.PropertyValueTextBox = new DevExpress.XtraEditors.TextEdit(); this.PropertyNameTextBox = new DevExpress.XtraEditors.TextEdit(); this.CancelButton = new DevExpress.XtraEditors.SimpleButton(); this.PropertiesGridControl = new DevExpress.XtraGrid.GridControl(); this.PropertiesGridView = new DevExpress.XtraGrid.Views.Grid.GridView(); this.LineCountSpinEdit = new DevExpress.XtraEditors.SpinEdit(); this.SampleCablePictureBox = new DevExpress.XtraEditors.PictureEdit(); this.CableCountSpinEdit = new DevExpress.XtraEditors.SpinEdit(); this.SaveButton = new DevExpress.XtraEditors.SimpleButton(); this.LenghtSpinEdit = new DevExpress.XtraEditors.SpinEdit(); this.CableModelTextBox = new DevExpress.XtraEditors.TextEdit(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem(); this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem8 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem10 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem11 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem12 = new DevExpress.XtraLayout.LayoutControlItem(); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar2 = new DevExpress.XtraBars.Bar(); this.btnNew = new DevExpress.XtraBars.BarButtonItem(); this.btnDetail = new DevExpress.XtraBars.BarButtonItem(); this.btnDelete = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.PropertyValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.PropertyValueTextBox.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertyNameTextBox.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertiesGridControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertiesGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.LineCountSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SampleCablePictureBox.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CableCountSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.LenghtSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CableModelTextBox.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertyValidator)).BeginInit(); this.SuspendLayout(); // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.AddPropertyButton); this.layoutControl1.Controls.Add(this.PropertyValueTextBox); this.layoutControl1.Controls.Add(this.PropertyNameTextBox); this.layoutControl1.Controls.Add(this.CancelButton); this.layoutControl1.Controls.Add(this.PropertiesGridControl); this.layoutControl1.Controls.Add(this.LineCountSpinEdit); this.layoutControl1.Controls.Add(this.SampleCablePictureBox); this.layoutControl1.Controls.Add(this.CableCountSpinEdit); this.layoutControl1.Controls.Add(this.SaveButton); this.layoutControl1.Controls.Add(this.LenghtSpinEdit); this.layoutControl1.Controls.Add(this.CableModelTextBox); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 26); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(551, 556); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // AddPropertyButton // this.AddPropertyButton.Location = new System.Drawing.Point(7, 250); this.AddPropertyButton.Name = "AddPropertyButton"; this.AddPropertyButton.Size = new System.Drawing.Size(538, 22); this.AddPropertyButton.StyleController = this.layoutControl1; this.AddPropertyButton.TabIndex = 15; this.AddPropertyButton.Text = "Add Property"; this.AddPropertyButton.Click += new System.EventHandler(this.AddPropertyButton_Click); // // PropertyValueTextBox // this.PropertyValueTextBox.Location = new System.Drawing.Point(125, 219); this.PropertyValueTextBox.Name = "PropertyValueTextBox"; this.PropertyValueTextBox.Size = new System.Drawing.Size(420, 20); this.PropertyValueTextBox.StyleController = this.layoutControl1; this.PropertyValueTextBox.TabIndex = 14; conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule1.ErrorText = "This value is not valid"; conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.PropertyValidator.SetValidationRule(this.PropertyValueTextBox, conditionValidationRule1); // // PropertyNameTextBox // this.PropertyNameTextBox.Location = new System.Drawing.Point(125, 188); this.PropertyNameTextBox.Name = "PropertyNameTextBox"; this.PropertyNameTextBox.Size = new System.Drawing.Size(420, 20); this.PropertyNameTextBox.StyleController = this.layoutControl1; this.PropertyNameTextBox.TabIndex = 13; conditionValidationRule2.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule2.ErrorText = "This value is not valid"; conditionValidationRule2.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.PropertyValidator.SetValidationRule(this.PropertyNameTextBox, conditionValidationRule2); // // CancelButton // this.CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CancelButton.Location = new System.Drawing.Point(417, 155); this.CancelButton.Name = "CancelButton"; this.CancelButton.Size = new System.Drawing.Size(128, 22); this.CancelButton.StyleController = this.layoutControl1; this.CancelButton.TabIndex = 11; this.CancelButton.Text = "Cancel"; // // PropertiesGridControl // this.PropertiesGridControl.Location = new System.Drawing.Point(7, 283); this.PropertiesGridControl.MainView = this.PropertiesGridView; this.PropertiesGridControl.Name = "PropertiesGridControl"; this.PropertiesGridControl.Size = new System.Drawing.Size(538, 267); this.PropertiesGridControl.TabIndex = 9; this.PropertiesGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.PropertiesGridView}); // // PropertiesGridView // this.PropertiesGridView.GridControl = this.PropertiesGridControl; this.PropertiesGridView.Name = "PropertiesGridView"; this.PropertiesGridView.OptionsView.ShowGroupPanel = false; this.PropertiesGridView.OptionsView.ShowIndicator = false; // // LineCountSpinEdit // this.LineCountSpinEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.LineCountSpinEdit.Location = new System.Drawing.Point(128, 121); this.LineCountSpinEdit.Name = "LineCountSpinEdit"; this.LineCountSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.LineCountSpinEdit.Size = new System.Drawing.Size(247, 20); this.LineCountSpinEdit.StyleController = this.layoutControl1; this.LineCountSpinEdit.TabIndex = 8; // // SampleCablePictureBox // this.SampleCablePictureBox.EditValue = ((object)(resources.GetObject("SampleCablePictureBox.EditValue"))); this.SampleCablePictureBox.Location = new System.Drawing.Point(386, 28); this.SampleCablePictureBox.Name = "SampleCablePictureBox"; this.SampleCablePictureBox.Size = new System.Drawing.Size(156, 113); this.SampleCablePictureBox.StyleController = this.layoutControl1; this.SampleCablePictureBox.TabIndex = 12; // // CableCountSpinEdit // this.CableCountSpinEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.CableCountSpinEdit.Location = new System.Drawing.Point(128, 90); this.CableCountSpinEdit.Name = "CableCountSpinEdit"; this.CableCountSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.CableCountSpinEdit.Size = new System.Drawing.Size(247, 20); this.CableCountSpinEdit.StyleController = this.layoutControl1; this.CableCountSpinEdit.TabIndex = 7; // // SaveButton // this.SaveButton.Location = new System.Drawing.Point(268, 155); this.SaveButton.Name = "SaveButton"; this.SaveButton.Size = new System.Drawing.Size(138, 22); this.SaveButton.StyleController = this.layoutControl1; this.SaveButton.TabIndex = 10; this.SaveButton.Text = "Save"; this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); // // LenghtSpinEdit // this.LenghtSpinEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.LenghtSpinEdit.Location = new System.Drawing.Point(128, 59); this.LenghtSpinEdit.Name = "LenghtSpinEdit"; this.LenghtSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.LenghtSpinEdit.Size = new System.Drawing.Size(247, 20); this.LenghtSpinEdit.StyleController = this.layoutControl1; this.LenghtSpinEdit.TabIndex = 6; // // CableModelTextBox // this.CableModelTextBox.Location = new System.Drawing.Point(128, 28); this.CableModelTextBox.Name = "CableModelTextBox"; this.CableModelTextBox.Size = new System.Drawing.Size(247, 20); this.CableModelTextBox.StyleController = this.layoutControl1; this.CableModelTextBox.TabIndex = 4; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem6, this.emptySpaceItem1, this.layoutControlItem7, this.layoutControlGroup2, this.layoutControlItem8, this.layoutControlItem10, this.layoutControlItem11, this.layoutControlItem12}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(551, 556); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem6 // this.layoutControlItem6.Control = this.PropertiesGridControl; this.layoutControlItem6.CustomizationFormText = "layoutControlItem6"; this.layoutControlItem6.Location = new System.Drawing.Point(0, 276); this.layoutControlItem6.Name = "layoutControlItem6"; this.layoutControlItem6.Size = new System.Drawing.Size(549, 278); this.layoutControlItem6.Text = "layoutControlItem6"; this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem6.TextToControlDistance = 0; this.layoutControlItem6.TextVisible = false; // // emptySpaceItem1 // this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1"; this.emptySpaceItem1.Location = new System.Drawing.Point(0, 148); this.emptySpaceItem1.Name = "emptySpaceItem1"; this.emptySpaceItem1.Size = new System.Drawing.Size(261, 33); this.emptySpaceItem1.Text = "emptySpaceItem1"; this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); // // layoutControlItem7 // this.layoutControlItem7.Control = this.SaveButton; this.layoutControlItem7.CustomizationFormText = "layoutControlItem7"; this.layoutControlItem7.Location = new System.Drawing.Point(261, 148); this.layoutControlItem7.Name = "layoutControlItem7"; this.layoutControlItem7.Size = new System.Drawing.Size(149, 33); this.layoutControlItem7.Text = "layoutControlItem7"; this.layoutControlItem7.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem7.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem7.TextToControlDistance = 0; this.layoutControlItem7.TextVisible = false; // // layoutControlGroup2 // this.layoutControlGroup2.CustomizationFormText = "layoutControlGroup2"; this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1, this.layoutControlItem3, this.layoutControlItem4, this.layoutControlItem5, this.layoutControlItem9}); this.layoutControlGroup2.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup2.Name = "layoutControlGroup2"; this.layoutControlGroup2.Size = new System.Drawing.Size(549, 148); this.layoutControlGroup2.Text = "layoutControlGroup2"; // // layoutControlItem1 // this.layoutControlItem1.Control = this.CableModelTextBox; this.layoutControlItem1.CustomizationFormText = "Cable Model"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(376, 31); this.layoutControlItem1.Text = "Cable Model"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem3 // this.layoutControlItem3.Control = this.LenghtSpinEdit; this.layoutControlItem3.CustomizationFormText = "Length"; this.layoutControlItem3.Location = new System.Drawing.Point(0, 31); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(376, 31); this.layoutControlItem3.Text = "Length"; this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem4 // this.layoutControlItem4.Control = this.CableCountSpinEdit; this.layoutControlItem4.CustomizationFormText = "Cable Count"; this.layoutControlItem4.Location = new System.Drawing.Point(0, 62); this.layoutControlItem4.Name = "layoutControlItem4"; this.layoutControlItem4.Size = new System.Drawing.Size(376, 31); this.layoutControlItem4.Text = "Cable Count in Package"; this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem4.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem5 // this.layoutControlItem5.Control = this.LineCountSpinEdit; this.layoutControlItem5.CustomizationFormText = "Line Count"; this.layoutControlItem5.Location = new System.Drawing.Point(0, 93); this.layoutControlItem5.Name = "layoutControlItem5"; this.layoutControlItem5.Size = new System.Drawing.Size(376, 31); this.layoutControlItem5.Text = "Line Count per Cable"; this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem5.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem9 // this.layoutControlItem9.Control = this.SampleCablePictureBox; this.layoutControlItem9.CustomizationFormText = "layoutControlItem9"; this.layoutControlItem9.Location = new System.Drawing.Point(376, 0); this.layoutControlItem9.Name = "layoutControlItem9"; this.layoutControlItem9.Size = new System.Drawing.Size(167, 124); this.layoutControlItem9.Text = "layoutControlItem9"; this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem9.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem9.TextToControlDistance = 0; this.layoutControlItem9.TextVisible = false; // // layoutControlItem8 // this.layoutControlItem8.Control = this.CancelButton; this.layoutControlItem8.CustomizationFormText = "layoutControlItem8"; this.layoutControlItem8.Location = new System.Drawing.Point(410, 148); this.layoutControlItem8.Name = "layoutControlItem8"; this.layoutControlItem8.Size = new System.Drawing.Size(139, 33); this.layoutControlItem8.Text = "layoutControlItem8"; this.layoutControlItem8.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem8.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem8.TextToControlDistance = 0; this.layoutControlItem8.TextVisible = false; // // layoutControlItem10 // this.layoutControlItem10.Control = this.PropertyNameTextBox; this.layoutControlItem10.CustomizationFormText = "Name"; this.layoutControlItem10.Location = new System.Drawing.Point(0, 181); this.layoutControlItem10.Name = "layoutControlItem10"; this.layoutControlItem10.Size = new System.Drawing.Size(549, 31); this.layoutControlItem10.Text = "Name"; this.layoutControlItem10.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem10.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem11 // this.layoutControlItem11.Control = this.PropertyValueTextBox; this.layoutControlItem11.CustomizationFormText = "Value"; this.layoutControlItem11.Location = new System.Drawing.Point(0, 212); this.layoutControlItem11.Name = "layoutControlItem11"; this.layoutControlItem11.Size = new System.Drawing.Size(549, 31); this.layoutControlItem11.Text = "Value"; this.layoutControlItem11.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem11.TextSize = new System.Drawing.Size(113, 20); // // layoutControlItem12 // this.layoutControlItem12.Control = this.AddPropertyButton; this.layoutControlItem12.CustomizationFormText = "layoutControlItem12"; this.layoutControlItem12.Location = new System.Drawing.Point(0, 243); this.layoutControlItem12.Name = "layoutControlItem12"; this.layoutControlItem12.Size = new System.Drawing.Size(549, 33); this.layoutControlItem12.Text = "layoutControlItem12"; this.layoutControlItem12.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem12.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem12.TextToControlDistance = 0; this.layoutControlItem12.TextVisible = false; // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar2}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.btnNew, this.btnDetail, this.btnDelete}); this.barManager1.MainMenu = this.bar2; this.barManager1.MaxItemId = 3; // // bar2 // this.bar2.BarName = "Main menu"; this.bar2.DockCol = 0; this.bar2.DockRow = 0; this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnNew), new DevExpress.XtraBars.LinkPersistInfo(this.btnDetail), new DevExpress.XtraBars.LinkPersistInfo(this.btnDelete)}); this.bar2.OptionsBar.AllowQuickCustomization = false; this.bar2.OptionsBar.DrawDragBorder = false; this.bar2.OptionsBar.MultiLine = true; this.bar2.OptionsBar.UseWholeRow = true; this.bar2.Text = "Main menu"; // // btnNew // this.btnNew.Caption = "New"; this.btnNew.Glyph = ((System.Drawing.Image)(resources.GetObject("btnNew.Glyph"))); this.btnNew.Id = 0; this.btnNew.Name = "btnNew"; // // btnDetail // this.btnDetail.Caption = "Detail"; this.btnDetail.Glyph = ((System.Drawing.Image)(resources.GetObject("btnDetail.Glyph"))); this.btnDetail.Id = 1; this.btnDetail.Name = "btnDetail"; // // btnDelete // this.btnDelete.Caption = "Delete"; this.btnDelete.Glyph = ((System.Drawing.Image)(resources.GetObject("btnDelete.Glyph"))); this.btnDelete.Id = 2; this.btnDelete.Name = "btnDelete"; // // NewCableModelForm // this.AcceptButton = this.SaveButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(551, 582); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "NewCableModelForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Cable Model"; this.Load += new System.EventHandler(this.CableModel_Load); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.PropertyValueTextBox.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertyNameTextBox.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertiesGridControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertiesGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.LineCountSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SampleCablePictureBox.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CableCountSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.LenghtSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CableModelTextBox.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.PropertyValidator)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraEditors.SpinEdit LineCountSpinEdit; private DevExpress.XtraEditors.SpinEdit CableCountSpinEdit; private DevExpress.XtraEditors.SpinEdit LenghtSpinEdit; private DevExpress.XtraEditors.TextEdit CableModelTextBox; private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar2; private DevExpress.XtraBars.BarButtonItem btnNew; private DevExpress.XtraBars.BarButtonItem btnDetail; private DevExpress.XtraBars.BarButtonItem btnDelete; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraGrid.GridControl PropertiesGridControl; private DevExpress.XtraGrid.Views.Grid.GridView PropertiesGridView; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6; private DevExpress.XtraEditors.SimpleButton CancelButton; private DevExpress.XtraEditors.SimpleButton SaveButton; private DevExpress.XtraEditors.PictureEdit SampleCablePictureBox; private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem8; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9; private DevExpress.XtraEditors.TextEdit PropertyNameTextBox; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem10; private DevExpress.XtraEditors.TextEdit PropertyValueTextBox; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem11; private DevExpress.XtraEditors.SimpleButton AddPropertyButton; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem12; private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider PropertyValidator; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Threading; namespace Apache.Geode.Client.UnitTests { using Apache.Geode.DUnitFramework; using Apache.Geode.Client; class TallyWriter<TKey, TVal> : CacheWriterAdapter<TKey, TVal> { #region Private members private int m_creates = 0; private int m_updates = 0; private int m_invalidates = 0; private int m_destroys = 0; private Object m_callbackArg = null; private int m_clears = 0; private Object m_lastKey = null; private Object m_lastValue = null; private bool isWriterFailed = false; private bool isWriterInvoke = false; private bool isCallbackCalled = false; #endregion #region Public accessors public int Creates { get { return m_creates; } } public int Clears { get { return m_clears; } } public int Updates { get { return m_updates; } } public int Invalidates { get { return m_invalidates; } } public int Destroys { get { return m_destroys; } } public Object LastKey { get { return m_lastKey; } } public Object CallbackArgument { get { return m_callbackArg; } } public Object LastValue { get { return m_lastValue; } } public void SetWriterFailed( ) { isWriterFailed = true; } public void SetCallBackArg( object callbackArg ) { m_callbackArg = callbackArg; } public void ResetWriterInvokation() { isWriterInvoke = false; isCallbackCalled = false; } public bool IsWriterInvoked { get { return isWriterInvoke; } } public bool IsCallBackArgCalled { get { return isCallbackCalled; } } #endregion public int ExpectCreates(int expected) { int tries = 0; while ((m_creates < expected) && (tries < 200)) { Thread.Sleep(100); tries++; } return m_creates; } public int ExpectUpdates(int expected) { int tries = 0; while ((m_updates < expected) && (tries < 200)) { Thread.Sleep(100); tries++; } return m_updates; } public void ShowTallies() { Util.Log("TallyWriter state: (updates = {0}, creates = {1}, invalidates = {2}, destroys = {3})", Updates, Creates, Invalidates, Destroys); } public void CheckcallbackArg<TKey1, TVal1>(EntryEvent<TKey1, TVal1> ev) { Util.Log("TallyWriterN: Checking callback arg for EntryEvent " + "key:{0} oldval: {1} newval:{2} cbArg:{3} for region:{4} and remoteOrigin:{5}", ev.Key, ev.NewValue, ev.OldValue, ev.CallbackArgument, ev.Region.Name, ev.RemoteOrigin); if(!isWriterInvoke) isWriterInvoke = true; /* if (m_callbackArg != null) { IGeodeSerializable callbkArg1 = ev.CallbackArgument as IGeodeSerializable; IGeodeSerializable callbkArg2 = m_callbackArg as IGeodeSerializable; if (callbkArg1 != null && callbkArg1.Equals(callbkArg2)) { isCallbackCalled = true; } string callbkArg3 = ev.CallbackArgument as string; string callbkArg4 = m_callbackArg as string; if (callbkArg3 != null && callbkArg3.Equals(callbkArg4)) { isCallbackCalled = true; } } * */ if (m_callbackArg != null && m_callbackArg.Equals(ev.CallbackArgument)) { isCallbackCalled = true; } } public static TallyWriter<TKey, TVal> Create() { return new TallyWriter<TKey, TVal>(); } #region ICacheWriter Members public override bool BeforeCreate(EntryEvent<TKey, TVal> ev) { m_creates++; Util.Log("TallyWriter::BeforeCreate"); CheckcallbackArg(ev); return !isWriterFailed; } public override bool BeforeDestroy(EntryEvent<TKey, TVal> ev) { m_destroys++; Util.Log("TallyWriter::BeforeDestroy"); CheckcallbackArg(ev); return !isWriterFailed; } public override bool BeforeRegionClear(RegionEvent<TKey, TVal> ev) { m_clears++; Util.Log("TallyWriter::BeforeRegionClear"); return true; } public override bool BeforeUpdate(EntryEvent<TKey, TVal> ev) { m_updates++; Util.Log("TallyWriter::BeforeUpdate"); CheckcallbackArg(ev); return !isWriterFailed; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualInt32() { var test = new SimpleBinaryOpTest__CompareEqualInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt32 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[ElementCount]; private static Int32[] _data2 = new Int32[ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32> _dataTable; static SimpleBinaryOpTest__CompareEqualInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt32(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) 2015 Alachisoft // // 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.Net; using System.Net.Sockets; using System.Threading; using Alachisoft.NCache.Web.Util; using Alachisoft.NCache.Caching; using ICallbackTask = Alachisoft.NCache.SocketServer.CallbackTasks.ICallbackTask; using IEventTask = Alachisoft.NCache.SocketServer.EventTask.IEventTask; using CallbackEntry = Alachisoft.NCache.Caching.CallbackEntry; using HelperFxn = Alachisoft.NCache.SocketServer.Util.HelperFxn; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Monitoring; using System.IO; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.SocketServer; using System.Collections.Generic; using Alachisoft.NCache.SocketServer.Statistics; #if !NET20 using System.Threading.Tasks; #endif namespace Alachisoft.NCache.SocketServer { /// <summary> /// This class is responsible for maitaining all clients connection with server. /// </summary> public sealed class ConnectionManager { #region ------------- Constants --------------- /// <summary> Number of maximam pending connections</summary> private int _maxClient = 100; /// <summary> Number of bytes that will hold the incomming command size</summary> internal const int cmdSizeHolderBytesCount = 10; /// <summary> Number of bytes that will hold the incomming data size</summary> internal const int valSizeHolderBytesCount = 10; /// <summary> Total number of bytes that will hold both command and data size</summary> internal const int totSizeHolderBytesCount = cmdSizeHolderBytesCount + valSizeHolderBytesCount; /// <summary> Total buffer size used as pinned buffer for asynchronous socket io.</summary> internal const int pinnedBufferSize = 200 * 1024; /// <summary> Total number of milliseconds after which we check for idle clients and send heart beat to them.</summary> internal const int waitIntervalHeartBeat = 30000; #endregion /// <summary> Underlying server socket object</summary> private Socket _serverSocket = null; /// <summary> Send buffer size of connected client socket</summary> private int _clientSendBufferSize = 0; /// <summary> Receive buffer size of connected client socket</summary> private int _clientReceiveBufferSize = 0; /// <summary> Command manager object to process incomming commands</summary> private ICommandManager cmdManager; /// <summary> Stores the client connections</summary> internal static Hashtable ConnectionTable = new Hashtable(10); /// <summary> Thread to send callback and notification responces to client</summary> private Thread _callbacksThread = null; /// <summary> Reade writer lock instance used to synchronize access to socket</summary> private static ReaderWriterLock _readerWriterLock = new ReaderWriterLock(); /// <summary> Hold server ip address</summary> private static string _serverIpAddress = string.Empty; /// <summary> Holds server port</summary> private static int _serverPort = -1; private Thread _eventsThread = null; private Logs _logger; private static LoggingInfo _clientLogginInfo = new LoggingInfo(); private static Queue _callbackQueue = new Queue(256); private static long _fragmentedMessageId; private static Thread _badClientMonitoringThread; private static int _timeOutInterval = int.MaxValue; //by default this interval is set to Max value i.e. infinity to turn off bad client detection private static bool _enableBadClientDetection = false; private DistributedQueue _eventsAndCallbackQueue; private PerfStatsCollector _perfStatsCollector; public ConnectionManager(PerfStatsCollector statsCollector) { _eventsAndCallbackQueue = new DistributedQueue(statsCollector); _perfStatsCollector = statsCollector; } internal static Queue CallbackQueue { get { return _callbackQueue; } } public PerfStatsCollector PerfStatsColl { get { return _perfStatsCollector; } } internal DistributedQueue EventsAndCallbackQueue { get { return _eventsAndCallbackQueue; } } /// <summary> /// Gets the fragmented unique message id /// </summary> private static long NextFragmentedMessageID { get { return Interlocked.Increment(ref _fragmentedMessageId); } } private static object _client_hearbeat_mutex = new object(); internal static object client_hearbeat_mutex { get { return _client_hearbeat_mutex; } } internal ICommandManager GetCommandManager(CommandManagerType cmdMgrType) { ICommandManager cmdMgr; switch (cmdMgrType) { case CommandManagerType.NCacheClient: cmdMgr = new CommandManager(_perfStatsCollector); break; case CommandManagerType.NCacheManagement: cmdMgr = new ManagementCommandManager(); break; default: cmdMgr = new CommandManager(_perfStatsCollector); break; } return cmdMgr; } private static int _messageFragmentSize = 512 * 1024; /// <summary> /// Start the socket server and start listening for clients /// <param name="port">port at which the server will be listening</param> /// </summary> /// public void Start(IPAddress bindIP, int port, int sendBuffer, int receiveBuffer, Logs logger, CommandManagerType cmdMgrType) { _logger = logger; _clientSendBufferSize = sendBuffer; _clientReceiveBufferSize = receiveBuffer; cmdManager = GetCommandManager(cmdMgrType); string maxPendingConnections="NCache.MaxPendingConnections"; string enableServerCounters = "NCache.EnableServerCounters"; if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableBadClientDetection"])) { try { _enableBadClientDetection = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableBadClientDetection"]); } catch (Exception e) { throw new Exception("Invalid value specified for NCacheServer.EnableBadClientDetection."); } if (_enableBadClientDetection) { if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.ClientSocketSendTimeOut"])) { try { _timeOutInterval = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.ClientSocketSendTimeOut"]); } catch (Exception e) { throw new Exception("Invalid value specified for NCacheServer.ClientSocketSendTimeOut."); } } if (_timeOutInterval < 5) _timeOutInterval = 5; } } string maxPendingCon = System.Configuration.ConfigurationSettings.AppSettings[maxPendingConnections]; if (maxPendingCon != null && maxPendingCon != String.Empty) { try { _maxClient = Convert.ToInt32(maxPendingCon); } catch (Exception e) { throw new Exception("Invalid value specified for " + maxPendingConnections + "."); } } string enablePerfCounters = System.Configuration.ConfigurationSettings.AppSettings[enableServerCounters]; if (enablePerfCounters != null && enablePerfCounters != String.Empty) { try { SocketServer.IsServerCounterEnabled = Convert.ToBoolean(enablePerfCounters); } catch (Exception e) { throw new Exception("Invalid value specified for " + enableServerCounters + "."); } } string maxRspLength = System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.MaxResponseLength"]; if (maxRspLength != null && maxRspLength != String.Empty) { try { int messageLength = Convert.ToInt32(maxRspLength); if (messageLength > 1) _messageFragmentSize = messageLength * 1024; } catch (Exception e) { throw new Exception("Invalid value specified for NCacheServer.MaxResponseLength."); } } _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (bindIP == null) { try { String hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName(hostName); bindIP = ipEntry.AddressList[0]; } catch (Exception e) { } } try { if (bindIP != null) _serverSocket.Bind(new IPEndPoint(bindIP, port)); else { _serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); } } catch (System.Net.Sockets.SocketException se) { switch (se.ErrorCode) { // 10049 --> address not available. case 10049: throw new Exception("The address " + bindIP + " specified for NCacheServer.BindToIP is not valid"); default: throw; } } _serverSocket.Listen(_maxClient); _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket); _serverIpAddress = ((IPEndPoint)_serverSocket.LocalEndPoint).Address.ToString(); if (cmdMgrType == CommandManagerType.NCacheClient) _serverPort = ((IPEndPoint)_serverSocket.LocalEndPoint).Port; _callbacksThread = new Thread(new ThreadStart(this.CallbackThread)); _callbacksThread.Priority = ThreadPriority.BelowNormal; _callbacksThread.Start(); _eventsThread = new Thread(new ThreadStart(this.SendBulkClientEvents)); _eventsThread.Name = "ConnectionManager.BulkEventThread"; _eventsThread.Start(); } /// <summary> /// Dipose socket server and all the allocated resources /// </summary> public void Stop() { DisposeServer(); } /// <summary> /// Dispose the client /// </summary> /// <param name="clientManager">Client manager object representing the client to be diposed</param> internal static void DisposeClient(ClientManager clientManager) { try { if (clientManager != null) { if (clientManager._leftGracefully) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " left gracefully"); } else { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", "Connection lost with client (" + clientManager.ToString() + ")"); } if (clientManager.ClientID != null) { lock (ConnectionTable) ConnectionTable.Remove(clientManager.ClientID); } clientManager.Dispose(); clientManager = null; } } catch (Exception) { } } private void AcceptCallback(IAsyncResult result) { Socket clientSocket = null; bool objectDisposed = false; try { clientSocket = ((Socket)result.AsyncState).EndAccept(result); } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "An error occured on EndAccept. " + e.ToString()); return; } finally { try { if (_serverSocket != null) _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket); } catch (ObjectDisposedException) { objectDisposed = true; } } if (objectDisposed) return; try { ClientManager clientManager = new ClientManager(this,clientSocket, totSizeHolderBytesCount, pinnedBufferSize); clientManager.ClientDisposed += new ClientDisposedCallback(OnClientDisposed); //Different network options depends on the underlying OS, which may support them or not //therefore we should handle error if they are not supported. try { clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, _clientSendBufferSize); } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set SendBuffer value. " + e.ToString()); } try { clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, _clientReceiveBufferSize); } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set ReceiveBuffer value. " + e.ToString()); } try { clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set NoDelay option. " + e.ToString()); } if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.AcceptCallback", "accepted client : " + clientSocket.RemoteEndPoint.ToString()); clientManager.ClientSocket.BeginReceive(clientManager.Buffer, 0, clientManager.discardingBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientManager); } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "can not set async receive callback Error " + e.ToString()); return; } } private static void UpdateContext(SendContext context, int dataSendOrReceived) { int remainingBytes = context.expectedSize - dataSendOrReceived; context.expectedSize = remainingBytes; context.offset += dataSendOrReceived; } internal void EnqueueEvent(Object eventObj, String slaveId) { { EventsAndCallbackQueue.Enqueue(eventObj, slaveId); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.SetEventQueueCountStats(EventsAndCallbackQueue.Count); } } private void ReceiveDiscardLength(IAsyncResult result) { SendContext context = (SendContext)result.AsyncState; ClientManager clientManager = context.clientManager; int bytesRecieved = 0; try { if (clientManager.ClientSocket == null) return; bytesRecieved = clientManager.ClientSocket.EndReceive(result); clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); if (bytesRecieved == 0) { DisposeClient(clientManager); return; } clientManager.MarkActivity(); if (bytesRecieved > clientManager.discardingBuffer.Length) if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionMgr.ReceiveCallback", " data read is more than the buffer"); if (bytesRecieved < context.expectedSize) { UpdateContext(context, bytesRecieved); clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(ReceiveDiscardLength), context); } context.buffer = clientManager.Buffer; if (bytesRecieved == context.expectedSize) { context.offset = 0; context.expectedSize = cmdSizeHolderBytesCount; clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(Receivelength), context); } } catch (SocketException so_ex) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString()); DisposeClient(clientManager); return; } catch (Exception e) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString()); DisposeClient(clientManager); return; } } private void Receivelength(IAsyncResult result) { SendContext context = (SendContext)result.AsyncState; ClientManager clientManager = context.clientManager; int bytesRecieved = 0; try { if (clientManager.ClientSocket == null) return; bytesRecieved = clientManager.ClientSocket.EndReceive(result); clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); if (bytesRecieved == 0) { DisposeClient(clientManager); return; } if (bytesRecieved < context.expectedSize) { UpdateContext(context, bytesRecieved); clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(Receivelength), context); } if (bytesRecieved == context.expectedSize) { long commandSize = 0; CommandContext(clientManager, out commandSize); int expectedCommandSize = (int)commandSize; context.buffer = clientManager.GetPinnedBuffer((int)expectedCommandSize); context.expectedSize = expectedCommandSize; context.offset = 0; context.totalExpectedSize = expectedCommandSize; clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(ReceiveCommmand), context); } } catch (SocketException so_ex) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString()); DisposeClient(clientManager); return; } catch (Exception e) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString()); DisposeClient(clientManager); return; } } private void ReceiveCommmand(IAsyncResult result) { SendContext context = (SendContext)result.AsyncState; ClientManager clientManager = context.clientManager; Alachisoft.NCache.Common.Protobuf.Command command = null; int bytesRecieved = 0; try { if (clientManager.ClientSocket == null) return; bytesRecieved = clientManager.ClientSocket.EndReceive(result); clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); if (bytesRecieved == 0) { DisposeClient(clientManager); return; } if (bytesRecieved < context.expectedSize) { UpdateContext(context, bytesRecieved); clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(ReceiveCommmand), context); } if (bytesRecieved == context.expectedSize) { byte[] buffer = context.buffer; using (MemoryStream stream = new MemoryStream(buffer, 0, (int)context.totalExpectedSize)) { command = ProtoBuf.Serializer.Deserialize<Alachisoft.NCache.Common.Protobuf.Command>(stream); stream.Close(); } clientManager.ReinitializeBuffer(); context = new SendContext(); context.clientManager = clientManager; context.buffer = clientManager.Buffer; context.expectedSize = clientManager.discardingBuffer.Length; clientManager.ClientSocket.BeginReceive(context.buffer, context.offset, context.expectedSize, SocketFlags.None, new AsyncCallback(ReceiveDiscardLength), context); if (ServerMonitor.MonitorActivity) { ServerMonitor.RegisterClient(clientManager.ClientID, clientManager.ClientSocketId); ServerMonitor.StartClientActivity(clientManager.ClientID); ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "enter"); } if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + command.type.ToString() + " RequestId :" + command.requestID); clientManager.AddToClientsRequest(1); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementRequestsPerSecStats(1); clientManager.StartCommandExecution(); cmdManager.ProcessCommand(clientManager, command); if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + command.type.ToString() + " RequestId :" + command.requestID); } } catch (SocketException so_ex) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString()); DisposeClient(clientManager); return; } catch (Exception e) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString()); if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + command + " Error " + e.ToString()); DisposeClient(clientManager); return; } finally { clientManager.StopCommandExecution(); if (ServerMonitor.MonitorActivity) ServerMonitor.StopClientActivity(clientManager.ClientID); } } private void CommandContext(ClientManager clientManager, out long tranSize) { int commandSize = HelperFxn.ToInt32(clientManager.Buffer, 0, cmdSizeHolderBytesCount, "Command"); tranSize = commandSize; byte[] buffer = clientManager.GetPinnedBuffer((int)tranSize); } private void RecieveCallback(IAsyncResult result) { ClientManager clientManager = (ClientManager)result.AsyncState; int bytesRecieved = 0; long transactionSize = 0; Object command = null; byte[] value = null; int discardingLength = 20; try { if (clientManager.ClientSocket == null) return; bytesRecieved = clientManager.ClientSocket.EndReceive(result); clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); if (bytesRecieved == 0) { DisposeClient(clientManager); return; } clientManager.MarkActivity(); if (bytesRecieved > discardingLength) if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionMgr.ReceiveCallback", " data read is more than the buffer"); if (bytesRecieved < discardingLength) { byte[] interimBuffer = new byte[discardingLength - bytesRecieved]; AssureRecieve(clientManager, ref interimBuffer); for (int i = 0; i < interimBuffer.Length; i++) clientManager.discardingBuffer[bytesRecieved + i] = interimBuffer[i]; bytesRecieved += interimBuffer.Length; } AssureRecieve(clientManager, ref clientManager.Buffer, cmdSizeHolderBytesCount); bytesRecieved += cmdSizeHolderBytesCount; Command.CommandBase cmd = null; AssureRecieve(clientManager, out command, out value, out transactionSize); transactionSize += bytesRecieved; if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "cmd_size :" + transactionSize); clientManager.ReinitializeBuffer(); clientManager.ClientSocket.BeginReceive( clientManager.discardingBuffer, 0, clientManager.discardingBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientManager); if (ServerMonitor.MonitorActivity) { ServerMonitor.RegisterClient(clientManager.ClientID, clientManager.ClientSocketId); ServerMonitor.StartClientActivity(clientManager.ClientID); ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "enter"); } clientManager.AddToClientsRequest(1); if (SocketServer.IsServerCounterEnabled) PerfStatsColl.IncrementRequestsPerSecStats(1); clientManager.StartCommandExecution(); cmdManager.ProcessCommand(clientManager, command); } catch (SocketException so_ex) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString()); DisposeClient(clientManager); return; } catch (Exception e) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString()); if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + command + " Error " + e.ToString()); DisposeClient(clientManager); return; } finally { clientManager.StopCommandExecution(); if (ServerMonitor.MonitorActivity) ServerMonitor.StopClientActivity(clientManager.ClientID); } } internal void OnClientDisposed(string clientSocketId) { if (ConnectionTable != null && clientSocketId != null) { lock (ConnectionTable) { ConnectionTable.Remove(clientSocketId); } } } internal static void AssureSend(ClientManager clientManager, byte[] buffer, Alachisoft.NCache.Common.Enum.Priority priority) { SendFragmentedResponse(clientManager, buffer, priority); } private static void AssureSend(ClientManager clientManager, byte[] buffer, Array userpayLoad, Alachisoft.NCache.Common.Enum.Priority priority) { SendContext context = new SendContext(); context.clientManager = clientManager; context.buffer = buffer; context.expectedSize = buffer.Length; try { bool doOperation = true; if (clientManager != null) { lock (clientManager) { doOperation = clientManager.MarkOperationInProcess(); if (!doOperation) { if (clientManager.IsDisposed) return; clientManager.PendingSendOperationQueue.add(context, priority); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementResponsesQueueCountStats(); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementResponsesQueueSizeStats(buffer.Length); return; } } AssureSend(clientManager, buffer, buffer.Length, context); } } catch (SocketException se) { DisposeClient(clientManager); } catch (ObjectDisposedException o) { return; } } internal void MonitorBadClients() { double sendTimeTaken; List<ClientManager> clients = new List<ClientManager>(); while (true) { try { clients.Clear(); lock (ConnectionManager.ConnectionTable) { ClientManager clientManager = null; IDictionaryEnumerator ide = ConnectionManager.ConnectionTable.GetEnumerator(); while (ide.MoveNext()) { clientManager = (ClientManager)ide.Value; clients.Add(clientManager); } } foreach (ClientManager client in clients) { if (client != null) { sendTimeTaken = client.TimeTakenByOperation(); if (sendTimeTaken > _timeOutInterval) { if (client.OperationInProgress) { ICommandExecuter cmdExecuter = client.CmdExecuter; if (cmdExecuter != null) cmdExecuter.OnClientForceFullyDisconnected(client.ClientID); client.ClientSocket.Disconnect(true); } } } } Thread.Sleep(5000); } catch (ThreadAbortException) { break; } catch (ThreadInterruptedException) { break; } catch (Exception ex) { } } } private static void SendFragmentedResponse(ClientManager client, byte[] bMessage, Alachisoft.NCache.Common.Enum.Priority priority) { if (bMessage != null) { //client older then 4.1 sp2 private patch 2 does not support message fragmentation. if (bMessage.Length <= _messageFragmentSize || client.ClientVersion < 4122) { AssureSend(client, bMessage, null, priority); } else { long messageId = NextFragmentedMessageID; int messageLength = bMessage.Length - cmdSizeHolderBytesCount; int noOfFragments = messageLength / _messageFragmentSize; if (bMessage.Length % _messageFragmentSize > 0) noOfFragments++; int srcOffset = cmdSizeHolderBytesCount; int remainingBytes = messageLength; Alachisoft.NCache.Common.Protobuf.FragmentedResponse fragmentedResponse = new Alachisoft.NCache.Common.Protobuf.FragmentedResponse(); for (int i = 0; i < noOfFragments; i++) { int chunkSize = remainingBytes > _messageFragmentSize ? _messageFragmentSize : remainingBytes; if (fragmentedResponse.message == null || fragmentedResponse.message.Length != chunkSize) fragmentedResponse.message = new byte[chunkSize]; Buffer.BlockCopy(bMessage, srcOffset, fragmentedResponse.message, 0, chunkSize); remainingBytes -= chunkSize; srcOffset += chunkSize; //fragmentedResponses.Add(fragmentedResponse); Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response(); response.requestId = -1; fragmentedResponse.messageId = messageId; fragmentedResponse.totalFragments = noOfFragments; fragmentedResponse.fragmentNo = i; response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.RESPONSE_FRAGMENT; response.getResponseFragment = fragmentedResponse; byte[] serializedReponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response); AssureSend(client, serializedReponse, null, priority); } } } } private static void Send(ClientManager clientManager, byte[] buffer, int count) { int bytesSent = 0; lock (clientManager.SendMutex) { while (bytesSent < count) { try { clientManager.ResetAsyncSendTime(); bytesSent += clientManager.ClientSocket.Send(buffer, bytesSent, count - bytesSent, SocketFlags.None); clientManager.AddToClientsBytesSent(bytesSent); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementBytesSentPerSecStats(bytesSent); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } } clientManager.ResetAsyncSendTime(); } } private static void AssureSend(ClientManager clientManager, byte[] buffer, int count, SendContext context) { try { Send(clientManager, buffer, count); lock (clientManager) { if (clientManager.PendingSendOperationQueue.Count == 0) { clientManager.DeMarkOperationInProcess(); return; } } #if !NET20 try { Task t = null; //as there are times in the queue; let's start sending pending responses in separate thread. TaskFactory factory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning); t = factory.StartNew(() => ProccessResponseQueue(clientManager), TaskCreationOptions.LongRunning); } catch (AggregateException aggEx) { } #else ThreadPool.QueueUserWorkItem(new WaitCallback(ProccessResponseQueue), clientManager); #endif } catch (Exception e) { if (SocketServer.Logger != null && SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AssureSend", e.ToString()); DisposeClient(clientManager); } } private static void ProccessResponseQueue(object arg) { ClientManager clientManager = arg as ClientManager; try { SendContext opContext = null; do { opContext = null; lock (clientManager) { if (clientManager.PendingSendOperationQueue.Count > 0) { object operation = clientManager.PendingSendOperationQueue.remove(); opContext = (SendContext)operation; clientManager.ResetAsyncSendTime(); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueCountStats(); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueSizeStats(opContext.expectedSize); } } if (opContext != null) { Send(opContext.clientManager, opContext.buffer, opContext.expectedSize); } lock (clientManager) { if (clientManager.PendingSendOperationQueue.Count == 0) { clientManager.DeMarkOperationInProcess(); return; } } } while (clientManager.PendingSendOperationQueue.Count > 0); } catch (Exception e) { if (SocketServer.Logger != null && SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AssureSend", e.ToString()); DisposeClient(clientManager); } } private static void AssureSendOld(ClientManager clientManager, byte[] buffer, int count, SendContext context) { TimeSpan tempTaken; try { Send(clientManager, buffer, count); SendContext opContext = null; do { opContext = null; lock (clientManager) { if (clientManager.PendingSendOperationQueue.Count > 0) { object operation = clientManager.PendingSendOperationQueue.remove(); opContext = (SendContext)operation; clientManager.ResetAsyncSendTime(); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueCountStats(); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueSizeStats(opContext.expectedSize); } } if (opContext != null) { Send(opContext.clientManager, opContext.buffer, opContext.expectedSize); } lock (clientManager) { if (clientManager.PendingSendOperationQueue.Count == 0) { clientManager.DeMarkOperationInProcess(); return; } } } while (clientManager.PendingSendOperationQueue.Count > 0); } catch (Exception e) { if (SocketServer.Logger != null && SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AssureSend", e.ToString()); DisposeClient(clientManager); } } private void AssureRecieve(ClientManager clientManager, out Object command, out byte[] value, out long tranSize) { value = null; int commandSize = HelperFxn.ToInt32(clientManager.Buffer, 0, cmdSizeHolderBytesCount, "Command"); tranSize = commandSize; byte[] buffer = clientManager.GetPinnedBuffer((int)tranSize); AssureRecieve(clientManager, ref buffer, (int)tranSize); command = cmdManager.Deserialize(buffer, commandSize); } /// <summary> /// Receives data equal to the buffer length. /// </summary> /// <param name="clientManager"></param> /// <param name="buffer"></param> private static void AssureRecieve(ClientManager clientManager, ref byte[] buffer) { int bytesRecieved = 0; int totalBytesReceived = 0; do { try { bytesRecieved = clientManager.ClientSocket.Receive(buffer, totalBytesReceived, buffer.Length - totalBytesReceived, SocketFlags.None); totalBytesReceived += bytesRecieved; clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } catch (ObjectDisposedException) { } } while (totalBytesReceived < buffer.Length && bytesRecieved > 0); } /// <summary> /// The Receives data less than the buffer size. i.e buffer length and size may not be equal. (used to avoid pinning of unnecessary byte buffers.) /// </summary> /// <param name="clientManager"></param> /// <param name="buffer"></param> /// <param name="size"></param> private static void AssureRecieve(ClientManager clientManager, ref byte[] buffer, int size) { int bytesRecieved = 0; int totalBytesReceived = 0; do { try { bytesRecieved = clientManager.ClientSocket.Receive(buffer, totalBytesReceived, size - totalBytesReceived, SocketFlags.None); totalBytesReceived += bytesRecieved; clientManager.AddToClientsBytesRecieved(bytesRecieved); if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } catch (ObjectDisposedException) { } } while (totalBytesReceived < size && bytesRecieved > 0); } private void SendBulkClientEvents() { Alachisoft.NCache.Common.Protobuf.Response response = null; QueuedItem item = null; string clienId = null; ClientManager clientManager = null; while (true) { try { item = (QueuedItem)_eventsAndCallbackQueue.Dequeue(); if (item != null) { if (SocketServer.IsServerCounterEnabled && PerfStatsColl != null) PerfStatsColl.SetEventQueueCountStats(_eventsAndCallbackQueue.Count); response = (Alachisoft.NCache.Common.Protobuf.Response)item.Item; clienId = item.RegisteredClientId; if (response != null) { if (clienId != null) { lock (ConnectionManager.ConnectionTable) { clientManager = (ClientManager)ConnectionManager.ConnectionTable[clienId]; } if (clientManager != null && clientManager.ClientVersion >= 4124) { try { byte[] serializedResponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response); ConnectionManager.AssureSend(clientManager, serializedResponse, Alachisoft.NCache.Common.Enum.Priority.Low); } catch (SocketException se) { clientManager.Dispose(); } catch (System.Exception ex) { if (SocketServer.IsServerCounterEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.EventThread", ex.ToString()); } } } else { if (SocketServer.IsServerCounterEnabled) SocketServer.Logger.NCacheLog.CriticalInfo("ConnectionManager.EventThread client information not found "); } } } } catch (ThreadAbortException ta) { break; } catch (ThreadInterruptedException ti) { break; } catch (Exception e) { } } } private void SendBulkEvents() { Alachisoft.NCache.Common.Protobuf.Response response; List<ClientManager> clients = new List<ClientManager>(); while (true) { try { clients.Clear(); bool takeBreak = true; lock (ConnectionManager.ConnectionTable) { ClientManager clientManager = null; IDictionaryEnumerator ide = ConnectionManager.ConnectionTable.GetEnumerator(); while (ide.MoveNext()) { clientManager = (ClientManager)ide.Value; if (clientManager.ClientVersion >= 4124) { clients.Add(clientManager); } } } foreach (ClientManager client in clients) { if (client != null) { try { bool hasMessages = false; response = client.GetEvents(out hasMessages); if (hasMessages && takeBreak) { takeBreak = false; } if (response != null) { byte[] serializedResponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response); ConnectionManager.AssureSend(client, serializedResponse, Alachisoft.NCache.Common.Enum.Priority.Low); } } catch (SocketException se) { client.Dispose(); } catch (InvalidOperationException io) { //thrown when iterator is modified break; } catch (Exception ex) { if (SocketServer.IsServerCounterEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.EventThread", ex.ToString()); } } } Thread.Sleep(500); } catch (ThreadAbortException ta) { break; } catch (ThreadInterruptedException ti) { break; } catch (Exception e) { if (SocketServer.IsServerCounterEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.EventThread", e.ToString()); } } } private void CallbackThread() { object returnVal = null; try { while (true) { while (CallbackQueue.Count > 0) { lock (CallbackQueue) returnVal = CallbackQueue.Dequeue(); try { if (returnVal is ICallbackTask) ((ICallbackTask)returnVal).Process(); else if (returnVal is IEventTask) ((IEventTask)returnVal).Process(); } catch (SocketException) { break; } catch (Exception) { } } lock (CallbackQueue) { Monitor.Wait(CallbackQueue); } } } catch (Exception) { } } public void StopListening() { if (_serverSocket != null) { _serverSocket.Close(); _serverSocket = null; } } private void DisposeServer() { StopListening(); if (_badClientMonitoringThread != null) _badClientMonitoringThread.Abort(); if (_eventsThread != null) _eventsThread.Abort(); if (_callbacksThread != null) { if (_callbacksThread.ThreadState != ThreadState.Aborted && _callbacksThread.ThreadState != ThreadState.AbortRequested) _callbacksThread.Abort(); } if (ConnectionTable != null) { lock (ConnectionTable) { Hashtable cloneTable = ConnectionTable.Clone() as Hashtable; IDictionaryEnumerator tableEnu = cloneTable.GetEnumerator(); while (tableEnu.MoveNext()) ((ClientManager)tableEnu.Value).Dispose(); } ConnectionTable = null; } } /// <summary> /// Set client logging info /// </summary> /// <param name="type"></param> /// <param name="status"></param> public static bool SetClientLoggingInfo(LoggingInfo.LoggingType type, LoggingInfo.LogsStatus status) { lock (_clientLogginInfo) { if (_clientLogginInfo.GetStatus(type) != status) { _clientLogginInfo.SetStatus(type, status); return true; } return false; } } /// <summary> /// Get client logging information /// </summary> public static LoggingInfo.LogsStatus GetClientLoggingInfo(LoggingInfo.LoggingType type) { lock (_clientLogginInfo) { return _clientLogginInfo.GetStatus(type); } } public static void UpdateClients() { bool errorOnly = false; bool detailed = false; lock (_clientLogginInfo) { errorOnly = GetClientLoggingInfo(LoggingInfo.LoggingType.Error) == LoggingInfo.LogsStatus.Enable; detailed = GetClientLoggingInfo(LoggingInfo.LoggingType.Detailed) == LoggingInfo.LogsStatus.Enable; } UpdateClients(errorOnly, detailed); } /// <summary> /// Update logging info on all connected clients /// </summary> private static void UpdateClients(bool errorOnly, bool detailed) { ICollection clients = null; lock (ConnectionTable) { clients = ConnectionTable.Values; } try { foreach (object obj in clients) { ClientManager client = obj as ClientManager; if (client != null) { NCache executor = client.CmdExecuter as NCache; if (executor != null) { executor.OnLoggingInfoModified(errorOnly, detailed, client.ClientID); } } } } catch (Exception exc) { throw; } } /// <summary> /// Get the ip address of server /// </summary> internal static string ServerIpAddress { get { return _serverIpAddress; } } /// <summary> /// Get the port at which server is running /// </summary> internal static int ServerPort { get { return _serverPort; } } } }
//Copyright 2017 Spin Services Limited //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.Threading.Tasks; using Akka.Actor; using NUnit.Framework; using SS.Integration.Adapter.Actors; using SS.Integration.Adapter.Actors.Messages; using SS.Integration.Adapter.Model; using SS.Integration.Adapter.Model.Enums; namespace SS.Integration.Adapter.Tests { [TestFixture] public class StreamStatsActorTests : AdapterTestKit { #region Constants public const string STREAM_STATS_ACTOR_CATEGORY = nameof(StreamStatsActor); #endregion #region SetUp [SetUp] public void SetupTest() { } #endregion #region Test Methods /// <summary> /// This test ensures we correctly increment snapshot count on Update Stats message /// </summary> [Test] [Category(STREAM_STATS_ACTOR_CATEGORY)] public void TestUpdateStatsSnapshotCount() { // //Arrange // var streamStatsActorRef = ActorOfAsTestActorRef<StreamStatsActor>( Props.Create(() => new StreamStatsActor()), StreamStatsActor.ActorName); var dateNow = DateTime.UtcNow; var updateStatsStartMsg = new AdapterProcessingStarted { UpdateReceivedAt = dateNow, Sequence = 1, IsSnapshot = true, Fixture = new Fixture { Id = "Fixture1Id", Sequence = 1, Epoch = 1, MatchStatus = MatchStatus.Prematch.ToString() } }; var updateStatsFinishMsg = new AdapterProcessingFinished { CompletedAt = dateNow.AddMilliseconds(1500) }; // //Act // streamStatsActorRef.Tell(updateStatsStartMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsFinishMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsStartMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsFinishMsg); // //Assert // AwaitAssert(() => { Assert.AreEqual(2, streamStatsActorRef.UnderlyingActor.SnapshotsCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.StreamUpdatesCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.DisconnectionsCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.PluginExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.ApiExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.GenericExceptionType]); Assert.AreEqual(DateTime.MinValue, streamStatsActorRef.UnderlyingActor.LastDisconnectedDate); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } /// <summary> /// This test ensures we correctly increment stream updates count on Update Stats message /// </summary> [Test] [Category(STREAM_STATS_ACTOR_CATEGORY)] public void TestUpdateStatsStreamUpdatesCount() { // //Arrange // var streamStatsActorRef = ActorOfAsTestActorRef<StreamStatsActor>( Props.Create(() => new StreamStatsActor()), StreamStatsActor.ActorName); var dateNow = DateTime.UtcNow; var updateStatsStartMsg = new AdapterProcessingStarted { UpdateReceivedAt = dateNow, Sequence = 1, IsSnapshot = false, Fixture = new Fixture { Id = "Fixture1Id", Sequence = 1, Epoch = 1, MatchStatus = MatchStatus.Prematch.ToString() } }; var updateStatsFinishMsg = new AdapterProcessingFinished { CompletedAt = dateNow.AddMilliseconds(1500) }; // //Act // streamStatsActorRef.Tell(updateStatsStartMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsFinishMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsStartMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(updateStatsFinishMsg); // //Assert // AwaitAssert(() => { Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.SnapshotsCount); Assert.AreEqual(2, streamStatsActorRef.UnderlyingActor.StreamUpdatesCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.DisconnectionsCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.PluginExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.ApiExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.GenericExceptionType]); Assert.AreEqual(DateTime.MinValue, streamStatsActorRef.UnderlyingActor.LastDisconnectedDate); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } /// <summary> /// This test ensures we correctly increment stream disconnections count on Update Stats message /// </summary> [Test] [Category(STREAM_STATS_ACTOR_CATEGORY)] public void TestUpdateStatsStreamDisconnectionsCount() { // //Arrange // var streamStatsActorRef = ActorOfAsTestActorRef<StreamStatsActor>( Props.Create(() => new StreamStatsActor()), StreamStatsActor.ActorName); var streamDisconnectedMsg = new StreamDisconnectedMsg(); // //Act // streamStatsActorRef.Tell(streamDisconnectedMsg); Task.Delay(TimeSpan.FromMilliseconds(500)); streamStatsActorRef.Tell(streamDisconnectedMsg); // //Assert // AwaitAssert(() => { Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.SnapshotsCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.StreamUpdatesCount); Assert.AreEqual(2, streamStatsActorRef.UnderlyingActor.DisconnectionsCount); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.PluginExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.ApiExceptionType]); Assert.AreEqual(0, streamStatsActorRef.UnderlyingActor.ErrorsCount[StreamStatsActor.GenericExceptionType]); Assert.Less((DateTime.UtcNow - streamStatsActorRef.UnderlyingActor.LastDisconnectedDate).TotalSeconds, 5); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } #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; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Mono.Addins; /***************************************************** * * XMLRPCModule * * Module for accepting incoming communications from * external XMLRPC client and calling a remote data * procedure for a registered data channel/prim. * * * 1. On module load, open a listener port * 2. Attach an XMLRPC handler * 3. When a request is received: * 3.1 Parse into components: channel key, int, string * 3.2 Look up registered channel listeners * 3.3 Call the channel (prim) remote data method * 3.4 Capture the response (llRemoteDataReply) * 3.5 Return response to client caller * 3.6 If no response from llRemoteDataReply within * RemoteReplyScriptTimeout, generate script timeout fault * * Prims in script must: * 1. Open a remote data channel * 1.1 Generate a channel ID * 1.2 Register primid,channelid pair with module * 2. Implement the remote data procedure handler * * llOpenRemoteDataChannel * llRemoteDataReply * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval) * llCloseRemoteDataChannel * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XMLRPCModule")] public class XMLRPCModule : ISharedRegionModule, IXMLRPC { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "XMLRPCModule"; // <channel id, RPCChannelInfo> private Dictionary<UUID, RPCChannelInfo> m_openChannels; private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses; private int m_remoteDataPort = 0; public int Port { get { return m_remoteDataPort; } } private Dictionary<UUID, RPCRequestInfo> m_rpcPending; private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses; private List<Scene> m_scenes = new List<Scene>(); private int RemoteReplyScriptTimeout = 9000; private int RemoteReplyScriptWait = 300; private object XMLRPCListLock = new object(); #region ISharedRegionModule Members public void Initialise(IConfigSource config) { // We need to create these early because the scripts might be calling // But since this gets called for every region, we need to make sure they // get called only one time (or we lose any open channels) m_openChannels = new Dictionary<UUID, RPCChannelInfo>(); m_rpcPending = new Dictionary<UUID, RPCRequestInfo>(); m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>(); m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>(); if (config.Configs["XMLRPC"] != null) { try { m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort); } catch (Exception) { } } } public void PostInitialise() { if (IsEnabled()) { // Start http server // Attach xmlrpc handlers // m_log.InfoFormat( // "[XML RPC MODULE]: Starting up XMLRPC Server on port {0} for llRemoteData commands.", // m_remoteDataPort); IHttpServer httpServer = MainServer.GetHttpServer((uint)m_remoteDataPort); httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); } } public void AddRegion(Scene scene) { if (!IsEnabled()) return; if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.RegisterModuleInterface<IXMLRPC>(this); } } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!IsEnabled()) return; if (m_scenes.Contains(scene)) { scene.UnregisterModuleInterface<IXMLRPC>(this); m_scenes.Remove(scene); } } public void Close() { } public string Name { get { return m_name; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IXMLRPC Members public bool IsEnabled() { return (m_remoteDataPort > 0); } /********************************************** * OpenXMLRPCChannel * * Generate a UUID channel key and add it and * the prim id to dictionary <channelUUID, primUUID> * * A custom channel key can be proposed. * Otherwise, passing UUID.Zero will generate * and return a random channel * * First check if there is a channel assigned for * this itemID. If there is, then someone called * llOpenRemoteDataChannel twice. Just return the * original channel. Other option is to delete the * current channel and assign a new one. * * ********************************************/ public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID) { UUID newChannel = UUID.Zero; // This should no longer happen, but the check is reasonable anyway if (null == m_openChannels) { m_log.Warn("[XML RPC MODULE]: Attempt to open channel before initialization is complete"); return newChannel; } //Is a dupe? foreach (RPCChannelInfo ci in m_openChannels.Values) { if (ci.GetItemID().Equals(itemID)) { // return the original channel ID for this item newChannel = ci.GetChannelID(); break; } } if (newChannel == UUID.Zero) { newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID; RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel); lock (XMLRPCListLock) { m_openChannels.Add(newChannel, rpcChanInfo); } } return newChannel; } // Delete channels based on itemID // for when a script is deleted public void DeleteChannels(UUID itemID) { if (m_openChannels != null) { ArrayList tmp = new ArrayList(); lock (XMLRPCListLock) { foreach (RPCChannelInfo li in m_openChannels.Values) { if (li.GetItemID().Equals(itemID)) { tmp.Add(itemID); } } IEnumerator tmpEnumerator = tmp.GetEnumerator(); while (tmpEnumerator.MoveNext()) m_openChannels.Remove((UUID) tmpEnumerator.Current); } } } /********************************************** * Remote Data Reply * * Response to RPC message * *********************************************/ public void RemoteDataReply(string channel, string message_id, string sdata, int idata) { UUID message_key = new UUID(message_id); UUID channel_key = new UUID(channel); RPCRequestInfo rpcInfo = null; if (message_key == UUID.Zero) { foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values) if (oneRpcInfo.GetChannelKey() == channel_key) rpcInfo = oneRpcInfo; } else { m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo); } if (rpcInfo != null) { rpcInfo.SetStrRetval(sdata); rpcInfo.SetIntRetval(idata); rpcInfo.SetProcessed(true); m_rpcPendingResponses.Remove(message_key); } else { m_log.Warn("[XML RPC MODULE]: Channel or message_id not found"); } } /********************************************** * CloseXMLRPCChannel * * Remove channel from dictionary * *********************************************/ public void CloseXMLRPCChannel(UUID channelKey) { if (m_openChannels.ContainsKey(channelKey)) m_openChannels.Remove(channelKey); } public bool hasRequests() { lock (XMLRPCListLock) { if (m_rpcPending != null) return (m_rpcPending.Count > 0); else return false; } } public IXmlRpcRequestInfo GetNextCompletedRequest() { if (m_rpcPending != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_rpcPending.Keys) { RPCRequestInfo tmpReq; if (m_rpcPending.TryGetValue(luid, out tmpReq)) { if (!tmpReq.IsProcessed()) return tmpReq; } } } } return null; } public void RemoveCompletedRequest(UUID id) { lock (XMLRPCListLock) { RPCRequestInfo tmp; if (m_rpcPending.TryGetValue(id, out tmp)) { m_rpcPending.Remove(id); m_rpcPendingResponses.Add(id, tmp); } else { m_log.Error("[XML RPC MODULE]: UNABLE TO REMOVE COMPLETED REQUEST"); } } } public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { SendRemoteDataRequest req = new SendRemoteDataRequest( localID, itemID, channel, dest, idata, sdata ); m_pendingSRDResponses.Add(req.GetReqID(), req); req.Process(); return req.ReqID; } public IServiceRequest GetNextCompletedSRDRequest() { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_pendingSRDResponses.Keys) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq)) { if (tmpReq.Finished) return tmpReq; } } } } return null; } public void RemoveCompletedSRDRequest(UUID id) { lock (XMLRPCListLock) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(id, out tmpReq)) { m_pendingSRDResponses.Remove(id); } } } public void CancelSRDRequests(UUID itemID) { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values) { if (li.ItemID.Equals(itemID)) m_pendingSRDResponses.Remove(li.GetReqID()); } } } } #endregion public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable) request.Params[0]; bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && requestData.Contains("StringValue")); if (GoodXML) { UUID channel = new UUID((string) requestData["Channel"]); RPCChannelInfo rpcChanInfo; if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) { string intVal = Convert.ToInt32(requestData["IntValue"]).ToString(); string strVal = (string) requestData["StringValue"]; RPCRequestInfo rpcInfo; lock (XMLRPCListLock) { rpcInfo = new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, intVal); m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); } int timeoutCtr = 0; while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) { Thread.Sleep(RemoteReplyScriptWait); timeoutCtr += RemoteReplyScriptWait; } if (rpcInfo.IsProcessed()) { Hashtable param = new Hashtable(); param["StringValue"] = rpcInfo.GetStrRetval(); param["IntValue"] = rpcInfo.GetIntRetval(); ArrayList parameters = new ArrayList(); parameters.Add(param); response.Value = parameters; rpcInfo = null; } else { response.SetFault(-1, "Script timeout"); rpcInfo = null; } } else { response.SetFault(-1, "Invalid channel"); } } return response; } } public class RPCRequestInfo: IXmlRpcRequestInfo { private UUID m_ChannelKey; private string m_IntVal; private UUID m_ItemID; private uint m_localID; private UUID m_MessageID; private bool m_processed; private int m_respInt; private string m_respStr; private string m_StrVal; public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal) { m_localID = localID; m_StrVal = strVal; m_IntVal = intVal; m_ItemID = itemID; m_ChannelKey = channelKey; m_MessageID = UUID.Random(); m_processed = false; m_respStr = String.Empty; m_respInt = 0; } public bool IsProcessed() { return m_processed; } public UUID GetChannelKey() { return m_ChannelKey; } public void SetProcessed(bool processed) { m_processed = processed; } public void SetStrRetval(string resp) { m_respStr = resp; } public string GetStrRetval() { return m_respStr; } public void SetIntRetval(int resp) { m_respInt = resp; } public int GetIntRetval() { return m_respInt; } public uint GetLocalID() { return m_localID; } public UUID GetItemID() { return m_ItemID; } public string GetStrVal() { return m_StrVal; } public int GetIntValue() { return int.Parse(m_IntVal); } public UUID GetMessageID() { return m_MessageID; } } public class RPCChannelInfo { private UUID m_ChannelKey; private UUID m_itemID; private uint m_localID; public RPCChannelInfo(uint localID, UUID itemID, UUID channelID) { m_ChannelKey = channelID; m_localID = localID; m_itemID = itemID; } public UUID GetItemID() { return m_itemID; } public UUID GetChannelID() { return m_ChannelKey; } public uint GetLocalID() { return m_localID; } } public class SendRemoteDataRequest: IServiceRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Channel; public string DestURL; private bool _finished; public bool Finished { get { return _finished; } set { _finished = value; } } private Thread httpThread; public int Idata; private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public XmlRpcRequest Request; public int ResponseIdata; public string ResponseSdata; public string Sdata; public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { this.Channel = channel; DestURL = dest; this.Idata = idata; this.Sdata = sdata; ItemID = itemID; LocalID = localID; ReqID = UUID.Random(); } public void Process() { _finished = false; httpThread = WorkManager.StartThread(SendRequest, "XMLRPCreqThread", ThreadPriority.BelowNormal, true, false, null, int.MaxValue); } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { Hashtable param = new Hashtable(); // Check if channel is an UUID // if not, use as method name UUID parseUID; string mName = "llRemoteData"; if (!string.IsNullOrEmpty(Channel)) if (!UUID.TryParse(Channel, out parseUID)) mName = Channel; else param["Channel"] = Channel; param["StringValue"] = Sdata; param["IntValue"] = Convert.ToString(Idata); ArrayList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest(mName, parameters); try { XmlRpcResponse resp = req.Send(DestURL, 30000); if (resp != null) { Hashtable respParms; if (resp.Value.GetType().Equals(typeof(Hashtable))) { respParms = (Hashtable) resp.Value; } else { ArrayList respData = (ArrayList) resp.Value; respParms = (Hashtable) respData[0]; } if (respParms != null) { if (respParms.Contains("StringValue")) { Sdata = (string) respParms["StringValue"]; } if (respParms.Contains("IntValue")) { Idata = Convert.ToInt32(respParms["IntValue"]); } if (respParms.Contains("faultString")) { Sdata = (string) respParms["faultString"]; } if (respParms.Contains("faultCode")) { Idata = Convert.ToInt32(respParms["faultCode"]); } } } } catch (Exception we) { Sdata = we.Message; m_log.Warn("[SendRemoteDataRequest]: Request failed"); m_log.Warn(we.StackTrace); } _finished = true; Watchdog.RemoveThread(); } public void Stop() { try { if (httpThread != null) { Watchdog.AbortThread(httpThread.ManagedThreadId); httpThread = null; } } catch (Exception) { } } public UUID GetReqID() { return ReqID; } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Linq; using Xunit; namespace Moq.Tests.Linq { public class UnsupportedQuerying { public class GivenAReadonlyNonVirtualProperty { [Fact] public void WhenQueryingDirect_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Bar>(x => x.NonVirtualValue == "bar")); } [Fact] public void WhenQueryingOnFluent_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Foo>(x => x.VirtualBar.NonVirtualValue == "bar")); } [Fact] public void WhenQueryingOnIntermediateFluentReadonly_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Foo>(x => x.NonVirtualBar.VirtualValue == "bar")); } public class Bar { public string NonVirtualValue { get { return "foo"; } } public virtual string VirtualValue { get; set; } } public class Foo { public virtual Bar VirtualBar { get; set; } public Bar NonVirtualBar { get; set; } } } public class GivenAField { [Fact] public void WhenQueryingField_ThenThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Mock.Of<Bar>(x => x.FieldValue == "bar")); } [Fact] public void WhenQueryingOnFluent_ThenThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Mock.Of<Foo>(x => x.VirtualBar.FieldValue == "bar")); } [Fact] public void WhenIntermediateFluentReadonly_ThenThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Mock.Of<Foo>(x => x.Bar.VirtualValue == "bar")); } public class Bar { public string FieldValue = "foo"; public virtual string VirtualValue { get; set; } } public class Foo { public Bar Bar = new Bar(); public virtual Bar VirtualBar { get; set; } } } public class GivenANonVirtualMethod { [Fact] public void WhenQueryingDirect_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Bar>(x => x.NonVirtual() == "foo")); } [Fact] public void WhenQueryingOnFluent_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Foo>(x => x.Virtual().NonVirtual() == "foo")); } [Fact] public void WhenQueryingOnIntermediateFluentNonVirtual_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<Foo>(x => x.NonVirtual().Virtual() == "foo")); } public class Bar { public string NonVirtual() { return string.Empty; } public virtual string Virtual() { return string.Empty; } } public class Foo { public Bar NonVirtual() { return new Bar(); } public virtual Bar Virtual() { return new Bar(); } } } public class GivenAnInterface { [Fact] public void WhenQueryingSingle_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().Single()); } [Fact] public void WhenQueryingSingleOrDefault_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().SingleOrDefault()); } [Fact] public void WhenQueryingAll_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().All(x => x.Value == "Foo")); } [Fact] public void WhenQueryingAny_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().Any()); } [Fact] public void WhenQueryingLast_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().Last()); } [Fact] public void WhenQueryingLastOrDefault_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mocks.Of<IFoo>().LastOrDefault()); } [Fact] public void WhenOperatorIsNotEqual_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Value != "foo")); } [Fact] public void WhenOperatorIsGreaterThan_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Count > 5)); } [Fact] public void WhenOperatorIsGreaterThanOrEqual_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Count >= 5)); } [Fact] public void WhenOperatorIsLessThan_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Count < 5)); } [Fact] public void WhenOperatorIsLessThanOrEqual_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Count <= 5)); } [Fact] public void WhenCombiningWithOrRatherThanLogicalAnd_ThenThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Mock.Of<IFoo>(x => x.Count == 5 || x.Value == "foo")); } public interface IFoo { string Value { get; set; } int Count { get; set; } } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.DataAccessLib; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Shared.Utilities; using Vevo.WebAppLib; using Vevo.WebUI; using Vevo.Base.Domain; using Vevo.Deluxe.Domain; using Vevo.Deluxe.Domain.DataInterfaces; using Vevo.Shared.DataAccess; public partial class AdminAdvanced_MainControls_AffiliatePayCommissionList : AdminAdvancedBaseUserControl { private GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null) ViewState["GridHelper"] = new GridViewHelper( uxGrid, "AffiliateCode" ); return (GridViewHelper) ViewState["GridHelper"]; } } private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContextDeluxe.AffiliateRepository.GetTableSchema(); uxSearchFilter.SetUpSchema( list ); } private void RefreshGrid() { int totalItems; uxGrid.DataSource = DataAccessContextDeluxe.AffiliateRepository.SearchAffiliateHaveBalance( GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, (uxPagingControl.CurrentPage - 1) * uxPagingControl.ItemsPerPages, (uxPagingControl.CurrentPage * uxPagingControl.ItemsPerPages) - 1, DataAccessContext.Configurations.GetDecimalValue( "AffiliateDefaultPaidBalance" ), GetStartDate(), GetEndDate(), out totalItems ); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); uxGrid.DataBind(); } private string GetStartDate() { if (uxPeriodDrop.SelectedValue == "Custom") { return uxStartDate.SelectedDateText; } else { return null; } } private string GetEndDate() { DateTime today = DateTime.Today; string endDate; if (uxPeriodDrop.SelectedValue == "LastMonth") { endDate = DateTimeUtilities.GetLastDayOfTheMonth( today.AddMonths( -1 ) ).ToLongDateString(); } else if (uxPeriodDrop.SelectedValue == "ThisMonth") { endDate = DateTimeUtilities.GetLastDayOfTheMonth( today ).ToLongDateString(); } else { endDate = uxEndDate.SelectedDateText; } return endDate; } private void PopulateNote() { uxLastMonthNoteLiteral.Visible = false; uxTodayNoteLiteral.Visible = false; uxCustomNoteLiteral.Visible = false; if (uxPeriodDrop.SelectedValue == "LastMonth") uxLastMonthNoteLiteral.Visible = true; else if (uxPeriodDrop.SelectedValue == "ThisMonth") uxTodayNoteLiteral.Visible = true; else uxCustomNoteLiteral.Visible = true; } private void PopulateControls() { if (!MainContext.IsPostBack) { RefreshGrid(); } if (uxGrid.Rows.Count > 0) { uxPagingControl.Visible = true; } else { uxPagingControl.Visible = false; } PopulateNote(); } private void uxGrid_RefreshHandler( object sender, EventArgs e ) { RefreshGrid(); } private void uxGrid_ResetPageHandler( object sender, EventArgs e ) { uxPagingControl.CurrentPage = 1; RefreshGrid(); } public string TotalPrice() { return DataAccessContextDeluxe.AffiliateRepository.GetTotalBalance( uxSearchFilter.SearchFilterObj, GetStartDate(), GetEndDate(), DataAccessContext.Configurations.GetDecimalValue( "AffiliateDefaultPaidBalance" ) ); } public void SetFooter( Object sender, GridViewRowEventArgs e ) { if (e.Row.RowType == DataControlRowType.Footer) { TableCellCollection cells = e.Row.Cells; cells.RemoveAt( 0 ); cells[0].ColumnSpan = 2; if (uxSearchFilter.SearchFilterObj.FilterType != SearchFilter.SearchFilterType.None) if (uxSearchFilter.SearchFilterObj.Value2 != "") if (uxSearchFilter.SearchFilterObj.FilterType == SearchFilter.SearchFilterType.Date) { cells[0].Text = uxSearchFilter.SearchFilterObj.FieldName + "<br> from " + DateTime.Parse( uxSearchFilter.SearchFilterObj.Value1 ).ToString( "MMMM d, yyyy" ) + " to " + DateTime.Parse( uxSearchFilter.SearchFilterObj.Value2 ).ToString( "MMMM d, yyyy" ); } else { cells[0].Text = uxSearchFilter.SearchFilterObj.FieldName + "<br> from " + uxSearchFilter.SearchFilterObj.Value1 + " to " + uxSearchFilter.SearchFilterObj.Value2; } else cells[0].Text = uxSearchFilter.SearchFilterObj.FieldName + " from " + uxSearchFilter.SearchFilterObj.Value1; else cells[0].Text = " Show All "; cells[0].CssClass = "pdl10"; cells[1].Text = "Total"; cells[1].HorizontalAlign = HorizontalAlign.Center; cells[1].Font.Bold = true; cells[2].Text = AdminUtilities.FormatPrice( Convert.ToDecimal( TotalPrice() ) ); cells[2].HorizontalAlign = HorizontalAlign.Right; } } protected void Page_Load( object sender, EventArgs e ) { if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName )) MainContext.RedirectMainControl( "Default.ascx", String.Empty ); uxSearchFilter.BubbleEvent += new EventHandler( uxGrid_ResetPageHandler ); uxPagingControl.BubbleEvent += new EventHandler( uxGrid_RefreshHandler ); if (!MainContext.IsPostBack) { uxPagingControl.ItemsPerPages = AdminConfig.AffiliatePaymentPerPage; SetUpSearchFilter(); uxNoteLiteral.Text = uxNoteLiteral.Text + " " + StoreContext.Currency.FormatPrice( DataAccessContext.Configurations.GetDecimalValue( "AffiliateDefaultPaidBalance" ) ); } } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); RefreshGrid(); } protected void uxPeriodDrop_SelectedIndexChanged( object sender, EventArgs e ) { if (uxPeriodDrop.SelectedValue == "Custom") uxCustomDatePanel.Visible = true; else { uxCustomDatePanel.Visible = false; RefreshGrid(); } } protected void uxDateRangeButton_Click( object sender, EventArgs e ) { if (uxPeriodDrop.SelectedValue == "Custom" && String.IsNullOrEmpty( uxStartDate.SelectedDateText ) && String.IsNullOrEmpty( uxEndDate.SelectedDateText )) return; RefreshGrid(); } }
using UnityEngine; using UnityEngine.Serialization; using XposeCraft.Core.Faction.Units; using XposeCraft.Core.Grids; using XposeCraft.Core.Required; using XposeCraft.Core.Resources; using XposeCraft.Game; using XposeCraft.Game.Actors.Buildings; using XposeCraft.Game.Actors.Units; using XposeCraft.Game.Enums; using XposeCraft.GameInternal; using Building = XposeCraft.Core.Required.Building; using BuildingHelper = XposeCraft.GameInternal.Helpers.BuildingHelper; using UnitType = XposeCraft.Core.Required.UnitType; namespace XposeCraft.Core.Faction.Buildings { public enum BuildingType { TempBuilding, ProgressBuilding, CompleteBuilding } [SelectionBase] public class BuildingController : MonoBehaviour { public Player PlayerOwner; public UnitType type; public BuildingType buildingType; public Building building; public new string name = "Building"; public int maxHealth = 100; public int health = 100; [FormerlySerializedAs("group")] public int FactionIndex; public SUnitBuilding unitProduction = new SUnitBuilding(); public STechBuilding techProduction = new STechBuilding(); public SBuildingGUI bGUI = new SBuildingGUI(); public SBuildingAnim anim = new SBuildingAnim(); public SGUI gui = new SGUI(); public TechEffect[] techEffect = new TechEffect[0]; public int loc; public float progressReq = 100; public float progressCur; public float progressPerRate; public int buildIndex; public float progressRate = 0.5f; public int garrison; public GameObject nextBuild; public int size = 1; public int gridI; public int index { get; set; } public int index1 { get; set; } public GUIManager manager { get; set; } bool selected; int[] nodeLoc; Health healthObj; UGrid grid; UnitSelection selection; private UnitController _lastBuildBy; private ResourceManager resourceManager { get { return GameManager.Instance.ResourceManagerFaction[FactionIndex]; } } protected Faction Faction { get { return GameManager.Instance.Factions[FactionIndex]; } } //bool displayGUI = false; //Progress progressObj; private void Awake() { var playerManager = GameObject.Find("Player Manager"); selection = playerManager.GetComponent<UnitSelection>(); manager = playerManager.GetComponent<GUIManager>(); gui.type = "Building"; if (buildingType == BuildingType.ProgressBuilding) { InvokeRepeating("Progress", 0, progressRate); } else if (buildingType == BuildingType.CompleteBuilding) { gameObject.name = name; gui.Awake(gameObject); for (int x = 0; x < techEffect.Length; x++) { Faction.Tech[techEffect[x].index].AddListener(gameObject); if (Faction.Tech[techEffect[x].index].active) { Upgraded(Faction.Tech[techEffect[x].index].name); } } } grid = GameObject.Find("UGrid").GetComponent<UGrid>(); healthObj = GetComponent<Health>(); //progressObj = GetComponent<Progress>(); } void Progress() { progressCur = progressCur + progressPerRate; } public bool RequestBuild(float amount, UnitController buildBy) { progressCur = progressCur + amount; _lastBuildBy = buildBy; return true; } public void FixedUpdate() { gui.Selected(selected); if (progressCur >= progressReq) { Place(); } if (buildingType != BuildingType.CompleteBuilding) { return; } if (unitProduction.canProduce) { unitProduction.Produce(this, Faction, FactionIndex, grid, gridI); } if (techProduction.canProduce) { techProduction.Produce(Faction); } } public void Select(bool state) { selected = state; } /// <summary> /// Replaces the current Progress building, which will get destoryed, by a complete building. /// </summary> /// <returns>Instance of the new completed building.</returns> public GameObject Place() { var placedBuilding = BuildingHelper.InstantiateFinishedBuilding( building, nextBuild, transform.position, loc, FactionIndex); if (!GameManager.Instance.ActorLookup.ContainsKey(gameObject)) { Destroy(gameObject); return placedBuilding.gameObject; } // The Actor was already created, so it will get updated and used in an event together with the builder var placedActor = (Game.Actors.Buildings.Building) GameManager.Instance.ActorLookup[gameObject]; placedActor.Placed(placedBuilding, PlayerOwner); // The ActorLookup gets modified in the process GameManager.Instance.ActorLookup.Remove(gameObject); GameManager.Instance.ActorLookup.Add(placedBuilding.gameObject, placedActor); Destroy(gameObject); GameManager.Instance.FiredEvent(PlayerOwner, GameEventType.BuildingCreated, new Arguments { MyUnit = (IUnit) GameManager.Instance.ActorLookup[_lastBuildBy.gameObject], MyBuilding = placedActor }); return placedBuilding.gameObject; } public void Damage(UnitType nType, int damage, GameObject attacker) { for (int x = 0; x < type.weaknesses.Length; x++) { if (type.weaknesses[x].targetName == nType.name) { damage = (int) (damage / type.weaknesses[x].amount); } } for (int x = 0; x < nType.strengths.Length; x++) { if (nType.strengths[x].targetName == type.name) { damage = (int) (damage * type.strengths[x].amount); } } health = health - damage; if (health <= 0) { Killed(); } else { // If still not destroyed, the Owner gets notified GameManager.Instance.FiredEvent(PlayerOwner, GameEventType.BuildingReceivedFire, new Arguments { EnemyUnits = new[] {(IUnit) GameManager.Instance.ActorLookup[attacker]}, MyBuilding = (IBuilding) GameManager.Instance.ActorLookup[gameObject] }); } } private void Killed() { building.OpenPoints(grid, gridI, loc); Destroy(gameObject); gui.Killed(gameObject); PlayerOwner.Buildings.Remove( GameManager.Instance.ActorLookup[gameObject] as Game.Actors.Buildings.Building); if (PlayerOwner.Buildings.Count == 0) { PlayerOwner.Lost(Player.LoseReason.AllBuildingsDestroyed); } } public void DisplayHealth() { if (healthObj) { healthObj.Display(); } } public void DisplayGUI(float ratioX, float ratioY) { int x1 = 0; int y1 = 0; for (int x = 0; x < unitProduction.units.Length; x++) { if (!unitProduction.units[x].canProduce) { continue; } if (bGUI.unitGUI.Display( x1, y1, unitProduction.units[x].customName, unitProduction.units[x].customTexture, ratioX, ratioY)) { unitProduction.StartProduction(x, resourceManager, GameManager.Instance.GuiPlayer); } if (bGUI.unitGUI.contains) { manager.mouseOverGUI = true; manager.mouseOverUnitProduction = true; manager.unitProductionIndex = x; } x1++; if (x1 < bGUI.unitGUI.buttonPerRow) { continue; } x1 = 0; y1++; } x1 = 0; y1 = 0; for (int x = 0; x < techProduction.techs.Length; x++) { if (!techProduction.techs[x].canProduce || Faction.Tech[techProduction.techs[x].index].beingProduced) { continue; } if (bGUI.technologyGUI.Display( x1, y1, techProduction.techs[x].customName, techProduction.techs[x].customTexture, ratioX, ratioY)) { techProduction.StartProduction(x, resourceManager); } if (bGUI.technologyGUI.contains) { manager.mouseOverGUI = true; manager.mouseOverTechProduction = true; manager.techProductionIndex = x; } x1++; if (x1 < bGUI.technologyGUI.buttonPerRow) { continue; } x1 = 0; y1++; } x1 = 0; y1 = 0; for (int x = 0; x < unitProduction.jobsAmount; x++) { if (bGUI.jobsGUI.Display( x1, y1, unitProduction.jobs[x].customName, unitProduction.jobs[x].customTexture, ratioX, ratioY)) { unitProduction.CancelProduction(x, resourceManager); } if (bGUI.jobsGUI.contains) { manager.mouseOverGUI = true; } x1++; if (x1 < bGUI.jobsGUI.buttonPerRow) { continue; } x1 = 0; y1++; } for (int x = 0; x < techProduction.jobsAmount; x++) { if (bGUI.jobsGUI.Display( x1, y1, techProduction.jobs[x].customName, techProduction.jobs[x].customTexture, ratioX, ratioY)) { techProduction.CancelProduction(x, Faction, resourceManager); } if (bGUI.jobsGUI.contains) { manager.mouseOverGUI = true; } x1++; if (x1 < bGUI.jobsGUI.buttonPerRow) { continue; } x1 = 0; y1++; } } void OnMouseDown() { selection.AddSelectedBuilding(gameObject); } public void Upgraded(string tech) { for (int x = 0; x < techEffect.Length; x++) { if (techEffect[x].name == tech) { techEffect[x].Replace(gameObject); } } } // Getters and Setters //{ // Name public string GetName() { return name; } public void SetName(string nVal) { name = nVal; } // Max Health public int GetMaxHealth() { return maxHealth; } public void SetMaxHealth(int nVal) { maxHealth = nVal; } public void AddMaxHealth(int nVal) { maxHealth += nVal; } public void SubMaxHealth(int nVal) { maxHealth -= nVal; } // Health public int GetHealth() { return health; } public void SetHealth(int nVal) { health = nVal; } public void AddHealth(int nVal) { health += nVal; } public void SubHealth(int nVal) { health -= nVal; } // Faction public int GetFaction() { return FactionIndex; } public void SetFaction(int factionIndex) { FactionIndex = factionIndex; } // Unit Can Produce public bool GetUCanProduce() { return unitProduction.canProduce; } public void SetUCanProduce(bool nVal) { unitProduction.canProduce = nVal; } // Unit Can Produce [Interior] public bool GetUICanProduce() { return unitProduction.units[index].canProduce; } public void SetUICanProduce(bool nVal) { unitProduction.units[index].canProduce = nVal; } // Unit Cost public int GetUCost() { return unitProduction.units[index].cost[index1]; } public void SetUCost(int nVal) { unitProduction.units[index].cost[index1] = nVal; } public void AddUCost(int nVal) { unitProduction.units[index].cost[index1] += nVal; } public void SubUCost(int nVal) { unitProduction.units[index].cost[index1] -= nVal; } // Unit Dur public float GetUDur() { return unitProduction.units[index].dur; } public void SetUDur(float nVal) { unitProduction.units[index].dur = nVal; } public void AddUDur(float nVal) { unitProduction.units[index].dur += nVal; } public void SubUDur(float nVal) { unitProduction.units[index].dur -= nVal; } // Unit Rate public float GetURate() { return unitProduction.units[index].rate; } public void SetURate(float nVal) { unitProduction.units[index].rate = nVal; } public void AddURate(float nVal) { unitProduction.units[index].rate += nVal; } public void SubURate(float nVal) { unitProduction.units[index].rate -= nVal; } // Unit JobsAmount public int GetUJobsAmount() { return unitProduction.jobsAmount; } // Unit CanBuildAtOnce public int GetUCanBuildAtOnce() { return unitProduction.canBuildAtOnce; } public void SetUCanBuildAtOnce(int nVal) { unitProduction.canBuildAtOnce = nVal; } public void AddUCanBuildAtOnce(int nVal) { unitProduction.canBuildAtOnce += nVal; } public void SubUCanBuildAtOnce(int nVal) { unitProduction.canBuildAtOnce -= nVal; } // Unit MaxAmount public int GetUMaxAmount() { return unitProduction.maxAmount; } public void SetUMaxAmount(int nVal) { unitProduction.maxAmount = nVal; } public void AddUMaxAmount(int nVal) { unitProduction.maxAmount += nVal; } public void SubUMaxAmount(int nVal) { unitProduction.maxAmount -= nVal; } // Tech Can Produce public bool GetTCanProduce() { return techProduction.canProduce; } public void SetTCanProduce(bool nVal) { techProduction.canProduce = nVal; } // Tech Can Produce [Interior] public bool GetTICanProduce() { return techProduction.techs[index].canProduce; } public void SetTICanProduce(bool nVal) { techProduction.techs[index].canProduce = nVal; } // Tech Cost public int GetTCost() { return techProduction.techs[index].cost[index1]; } public void SetTCost(int nVal) { techProduction.techs[index].cost[index1] = nVal; } public void AddTCost(int nVal) { techProduction.techs[index].cost[index1] += nVal; } public void SubTCost(int nVal) { techProduction.techs[index].cost[index1] -= nVal; } // Tech Dur public float GetTDur() { return techProduction.techs[index].dur; } public void SetTDur(float nVal) { techProduction.techs[index].dur = nVal; } public void AddTDur(float nVal) { techProduction.techs[index].dur += nVal; } public void SubTDur(float nVal) { techProduction.techs[index].dur -= nVal; } // Tech Rate public float GetTRate() { return techProduction.techs[index].rate; } public void SetTRate(float nVal) { techProduction.techs[index].rate = nVal; } public void AddTRate(float nVal) { techProduction.techs[index].rate += nVal; } public void SubTRate(float nVal) { techProduction.techs[index].rate -= nVal; } // Tech Jobs Amount public int GetTJobsAmount() { return techProduction.jobsAmount; } // Tech MaxAmount public int GetTMaxAmount() { return techProduction.maxAmount; } public void SetTMaxAmount(int nVal) { techProduction.maxAmount = nVal; } public void AddMTaxAmount(int nVal) { techProduction.maxAmount += nVal; } public void SubTMaxAmount(int nVal) { techProduction.maxAmount -= nVal; } // Tech CanBuildAtOnce public int GetTCanBuildAtOnce() { return techProduction.canBuildAtOnce; } public void SetTCanBuildAtOnce(int nVal) { techProduction.canBuildAtOnce = nVal; } public void AddTCanBuildAtOnce(int nVal) { techProduction.canBuildAtOnce += nVal; } public void SubTCanBuildAtOnce(int nVal) { techProduction.canBuildAtOnce -= nVal; } public void SetIndex(int nVal) { index = nVal; } public void SetIndex1(int nVal) { index1 = nVal; } //} } }
// // IFDRenderer.cs: Outputs an IFD structure into TIFF IFD bytes. // // Author: // Ruben Vermeersch (ruben@savanne.be) // Mike Gemuende (mike@gemuende.de) // // Copyright (C) 2009 Ruben Vermeersch // Copyright (C) 2009 Mike Gemuende // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; using System.Collections.Generic; using TagLib.IFD.Entries; namespace TagLib.IFD { /// <summary> /// This class contains all the IFD rendering code. /// </summary> public class IFDRenderer { #region Private Fields /// <summary> /// The IFD structure that will be rendered. /// </summary> private readonly IFDStructure structure; /// <summary> /// If IFD should be encoded in BigEndian or not. /// </summary> private readonly bool is_bigendian; /// <summary> /// A <see cref="System.UInt32"/> value with the offset of the /// current IFD. All offsets inside the IFD must be adjusted /// according to this given offset. /// </summary> private readonly uint ifd_offset; #endregion #region Constructors /// <summary> /// Constructor. Will render the given IFD structure. /// </summary> /// <param name="is_bigendian"> /// If IFD should be encoded in BigEndian or not. /// </param> /// <param name="structure"> /// The IFD structure that will be rendered. /// </param> /// <param name="ifd_offset"> /// A <see cref="System.UInt32"/> value with the offset of the /// current IFD. All offsets inside the IFD must be adjusted /// according to this given offset. /// </param> public IFDRenderer (bool is_bigendian, IFDStructure structure, uint ifd_offset) { this.is_bigendian = is_bigendian; this.structure = structure; this.ifd_offset = ifd_offset; } #endregion #region Public Methods /// <summary> /// Renders the current instance to a <see cref="ByteVector"/>. /// </summary> /// <returns> /// A <see cref="ByteVector"/> containing the rendered IFD. /// </returns> public ByteVector Render () { ByteVector ifd_data = new ByteVector (); uint current_offset = ifd_offset; var directories = structure.directories; for (int index = 0; index < directories.Count; index++) { ByteVector data = RenderIFD (directories [index], current_offset, index == directories.Count - 1); current_offset += (uint) data.Count; ifd_data.Add (data); } return ifd_data; } #endregion #region Private Methods /// <summary> /// Renders the IFD to an ByteVector where the offset of the IFD /// itself is <paramref name="ifd_offset"/> and all offsets /// contained in the IFD are adjusted accroding it. /// </summary> /// <param name="directory"> /// A <see cref="IFDDirectory"/> with the directory to render. /// </param> /// <param name="ifd_offset"> /// A <see cref="System.UInt32"/> with the offset of the IFD /// </param> /// <param name="last"> /// A <see cref="System.Boolean"/> which is true, if the IFD is /// the last one, i.e. the offset to the next IFD, which is /// stored inside the IFD, is 0. If the value is false, the /// offset to the next IFD is set that it starts directly after /// the current one. /// </param> /// <returns> /// A <see cref="ByteVector"/> with the rendered IFD. /// </returns> private ByteVector RenderIFD (IFDDirectory directory, uint ifd_offset, bool last) { if (directory.Count > (int)UInt16.MaxValue) throw new Exception (String.Format ("Directory has too much entries: {0}", directory.Count)); // Remove empty SUB ifds. var tags = new List<ushort> (directory.Keys); foreach (var tag in tags) { var entry = directory [tag]; if (entry is SubIFDEntry && (entry as SubIFDEntry).ChildCount == 0) { directory.Remove (tag); } } ushort entry_count = (ushort) directory.Count; // ifd_offset + size of entry_count + entries + next ifd offset uint data_offset = ifd_offset + 2 + 12 * (uint) entry_count + 4; // store the entries itself ByteVector entry_data = new ByteVector (); // store the data referenced by the entries ByteVector offset_data = new ByteVector (); entry_data.Add (ByteVector.FromUShort (entry_count, is_bigendian)); foreach (IFDEntry entry in directory.Values) RenderEntryData (entry, entry_data, offset_data, data_offset); if (last) entry_data.Add ("\0\0\0\0"); else entry_data.Add (ByteVector.FromUInt ((uint) (data_offset + offset_data.Count), is_bigendian)); if (data_offset - ifd_offset != entry_data.Count) throw new Exception (String.Format ("Expected IFD data size was {0} but is {1}", data_offset - ifd_offset, entry_data.Count)); entry_data.Add (offset_data); return entry_data; } #endregion #region Protected Methods /// <summary> /// Adds the data of a single entry to <paramref name="entry_data"/>. /// </summary> /// <param name="entry_data"> /// A <see cref="ByteVector"/> to add the entry to. /// </param> /// <param name="tag"> /// A <see cref="System.UInt16"/> with the tag of the entry. /// </param> /// <param name="type"> /// A <see cref="System.UInt16"/> with the type of the entry. /// </param> /// <param name="count"> /// A <see cref="System.UInt32"/> with the data count of the entry, /// </param> /// <param name="offset"> /// A <see cref="System.UInt32"/> with the offset field of the entry. /// </param> protected void RenderEntry (ByteVector entry_data, ushort tag, ushort type, uint count, uint offset) { entry_data.Add (ByteVector.FromUShort (tag, is_bigendian)); entry_data.Add (ByteVector.FromUShort (type, is_bigendian)); entry_data.Add (ByteVector.FromUInt (count, is_bigendian)); entry_data.Add (ByteVector.FromUInt (offset, is_bigendian)); } /// <summary> /// Renders a complete entry together with the data. The entry itself /// is stored in <paramref name="entry_data"/> and the data of the /// entry is stored in <paramref name="offset_data"/> if it cannot be /// stored in the offset. This method is called for every <see /// cref="IFDEntry"/> of this IFD and can be overwritten in subclasses /// to provide special behavior. /// </summary> /// <param name="entry"> /// A <see cref="IFDEntry"/> with the entry to render. /// </param> /// <param name="entry_data"> /// A <see cref="ByteVector"/> to add the entry to. /// </param> /// <param name="offset_data"> /// A <see cref="ByteVector"/> to add the entry data to if it cannot be /// stored in the offset field. /// </param> /// <param name="data_offset"> /// A <see cref="System.UInt32"/> with the offset, were the data of the /// entries starts. It is needed to adjust the offsets of the entries /// itself. /// </param> protected virtual void RenderEntryData (IFDEntry entry, ByteVector entry_data, ByteVector offset_data, uint data_offset) { ushort tag = (ushort) entry.Tag; uint offset = (uint) (data_offset + offset_data.Count); ushort type; uint count; ByteVector data = entry.Render (is_bigendian, offset, out type, out count); // store data in offset, if it is smaller than 4 byte if (data.Count <= 4) { while (data.Count < 4) data.Add ("\0"); offset = data.ToUInt (is_bigendian); data = null; } // preserve word boundary of offsets if (data != null && data.Count % 2 != 0) data.Add ("\0"); RenderEntry (entry_data, tag, type, count, offset); offset_data.Add (data); } /// <summary> /// Constructs a new IFD Renderer used to render a <see cref="SubIFDEntry"/>. /// </summary> /// <param name="is_bigendian"> /// If IFD should be encoded in BigEndian or not. /// </param> /// <param name="structure"> /// The IFD structure that will be rendered. /// </param> /// <param name="ifd_offset"> /// A <see cref="System.UInt32"/> value with the offset of the /// current IFD. All offsets inside the IFD must be adjusted /// according to this given offset. /// </param> protected virtual IFDRenderer CreateSubRenderer (bool is_bigendian, IFDStructure structure, uint ifd_offset) { return new IFDRenderer (is_bigendian, structure, ifd_offset); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using UnityEngine; namespace InControl { /// <summary> /// An action set represents a set of actions, usually for a single player. This class must be subclassed to be used. /// An action set can contain both explicit, bindable single value actions (for example, "Jump", "Left" and "Right") and implicit, /// aggregate actions which combine together other actions into one or two axes, for example "Move", which might consist /// of "Left", "Right", "Up" and "Down" filtered into a single two-axis control with its own applied circular deadzone, /// queryable vector value, etc. /// </summary> public abstract class PlayerActionSet { /// <summary> /// The device which this set should query from, if applicable. /// When set to <c>null</c> this set will query <see cref="InputManager.ActiveDevice" /> when required. /// </summary> public InputDevice Device { get; set; } /// <summary> /// Gets the actions in this set as a readonly collection. /// </summary> public ReadOnlyCollection<PlayerAction> Actions { get; private set; } /// <summary> /// Configures how in an action in this set listens for new bindings when the action does not /// explicitly define its own listen options. /// </summary> public BindingListenOptions ListenOptions = new BindingListenOptions(); /// <summary> /// The last update tick on which any action in this set changed value. /// </summary> public ulong UpdateTick { get; protected set; } /// <summary> /// The binding source type that provided input to this action set. /// </summary> public BindingSourceType LastInputType = BindingSourceType.None; /// <summary> /// Whether this action set should produce input. Default: <c>true</c> /// </summary> public bool Enabled { get; set; } List<PlayerAction> actions = new List<PlayerAction>(); List<PlayerOneAxisAction> oneAxisActions = new List<PlayerOneAxisAction>(); List<PlayerTwoAxisAction> twoAxisActions = new List<PlayerTwoAxisAction>(); Dictionary<string, PlayerAction> actionsByName = new Dictionary<string, PlayerAction>(); internal PlayerAction listenWithAction; protected PlayerActionSet() { Actions = new ReadOnlyCollection<PlayerAction>( actions ); Enabled = true; InputManager.OnUpdate -= Update; InputManager.OnUpdate += Update; } /// <summary> /// Properly dispose of this action set. You should make sure to call this when the action set /// will no longer be used or it will result in unnecessary internal processing every frame. /// </summary> public void Destroy() { InputManager.OnUpdate -= Update; } /// <summary> /// Create an action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <param name="name">A unique identifier for this action within the context of this set.</param> /// <exception cref="InControlException">Thrown when trying to create an action with a non-unique name for this set.</exception> protected PlayerAction CreatePlayerAction( string name ) { var action = new PlayerAction( name, this ); action.Device = Device ?? InputManager.ActiveDevice; if (actionsByName.ContainsKey( name )) { throw new InControlException( "Action '" + name + "' already exists in this set." ); } actions.Add( action ); actionsByName.Add( name, action ); return action; } /// <summary> /// Create an aggregate, single-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <example> /// <code> /// Throttle = CreateOneAxisPlayerAction( Brake, Accelerate ); /// </code> /// </example> /// <param name="negativeAction">The action to query for the negative component of the axis.</param> /// <param name="positiveAction">The action to query for the positive component of the axis.</param> protected PlayerOneAxisAction CreateOneAxisPlayerAction( PlayerAction negativeAction, PlayerAction positiveAction ) { var action = new PlayerOneAxisAction( negativeAction, positiveAction ); oneAxisActions.Add( action ); return action; } /// <summary> /// Create an aggregate, double-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <example> /// Note that, due to Unity's positive up-vector, the parameter order of <c>negativeYAction</c> and <c>positiveYAction</c> might seem counter-intuitive. /// <code> /// Move = CreateTwoAxisPlayerAction( Left, Right, Down, Up ); /// </code> /// </example> /// <param name="negativeXAction">The action to query for the negative component of the X axis.</param> /// <param name="positiveXAction">The action to query for the positive component of the X axis.</param> /// <param name="negativeYAction">The action to query for the negative component of the Y axis.</param> /// <param name="positiveYAction">The action to query for the positive component of the Y axis.</param> protected PlayerTwoAxisAction CreateTwoAxisPlayerAction( PlayerAction negativeXAction, PlayerAction positiveXAction, PlayerAction negativeYAction, PlayerAction positiveYAction ) { var action = new PlayerTwoAxisAction( negativeXAction, positiveXAction, negativeYAction, positiveYAction ); twoAxisActions.Add( action ); return action; } void Update( ulong updateTick, float deltaTime ) { var device = Device ?? InputManager.ActiveDevice; var actionsCount = actions.Count; for (int i = 0; i < actionsCount; i++) { var action = actions[i]; action.Update( updateTick, deltaTime, device ); if (action.UpdateTick > UpdateTick) { UpdateTick = action.UpdateTick; LastInputType = action.LastInputType; } } var oneAxisActionsCount = oneAxisActions.Count; for (int i = 0; i < oneAxisActionsCount; i++) { oneAxisActions[i].Update( updateTick, deltaTime ); } var twoAxisActionsCount = twoAxisActions.Count; for (int i = 0; i < twoAxisActionsCount; i++) { twoAxisActions[i].Update( updateTick, deltaTime ); } } /// <summary> /// Reset the bindings on all actions in this set. /// </summary> public void Reset() { var actionCount = actions.Count; for (int i = 0; i < actionCount; i++) { actions[i].ResetBindings(); } } internal bool HasBinding( BindingSource binding ) { if (binding == null) { return false; } var actionsCount = actions.Count; for (int i = 0; i < actionsCount; i++) { if (actions[i].HasBinding( binding )) { return true; } } return false; } internal void RemoveBinding( BindingSource binding ) { if (binding == null) { return; } var actionsCount = actions.Count; for (int i = 0; i < actionsCount; i++) { actions[i].FindAndRemoveBinding( binding ); } } /// <summary> /// Returns the state of this action set and all bindings encoded into a string /// that you can save somewhere. /// Pass this string to Load() to restore the state of this action set. /// </summary> public string Save() { using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter( stream, System.Text.Encoding.UTF8 )) { // Write header. writer.Write( (byte) 'B' ); writer.Write( (byte) 'I' ); writer.Write( (byte) 'N' ); writer.Write( (byte) 'D' ); // Write version. writer.Write( (UInt16) 1 ); // Write actions. var actionCount = actions.Count; writer.Write( actionCount ); for (int i = 0; i < actionCount; i++) { actions[i].Save( writer ); } } return Convert.ToBase64String( stream.ToArray() ); } } /// <summary> /// Load a state returned by calling Dump() at a prior time. /// </summary> /// <param name="data">The data string.</param> public void Load( string data ) { if (data == null) { return; } try { using (var stream = new MemoryStream( Convert.FromBase64String( data ) )) { using (var reader = new BinaryReader( stream )) { if (reader.ReadUInt32() != 0x444E4942) { throw new Exception( "Unknown data format." ); } if (reader.ReadUInt16() != 1) { throw new Exception( "Unknown data version." ); } var actionCount = reader.ReadInt32(); for (int i = 0; i < actionCount; i++) { PlayerAction action; if (actionsByName.TryGetValue( reader.ReadString(), out action )) { action.Load( reader ); } } } } } catch (Exception e) { Debug.LogError( "Provided state could not be loaded:\n" + e.Message ); Reset(); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Web.Core.Calendars; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace ASC.Api.Calendar.Test { [TestClass] public class RecurrenceRuleTest { private DateTime _toDate = new DateTime(2013, 6, 10, 9, 0, 0); private DateTime _fromDate = new DateTime(1990, 6, 10, 9, 0, 0); [TestMethod] public void YearlyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Count = 10, ByMonth = new int[] { 6, 7 } }; var dates = r1.GetDates(new DateTime(1997, 6, 10, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){new DateTime(1997, 6, 10, 9, 0, 0), new DateTime(1997, 7, 10, 9, 0, 0), new DateTime(1998, 6, 10, 9, 0, 0),new DateTime(1998, 7, 10, 9, 0, 0), new DateTime(1999, 6, 10, 9, 0, 0),new DateTime(1999, 7, 10, 9, 0, 0), new DateTime(2000, 6, 10, 9, 0, 0),new DateTime(2000, 7, 10, 9, 0, 0), new DateTime(2001, 6, 10, 9, 0, 0),new DateTime(2001, 7, 10, 9, 0, 0)}, dates); //test 2 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Interval = 2, Count = 10, ByMonth = new int[] { 1, 2,3 } }; dates = r1.GetDates(new DateTime(1997, 3, 10, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){new DateTime(1997, 3, 10, 9, 0, 0), new DateTime(1999, 1, 10, 9, 0, 0),new DateTime(1999, 2, 10, 9, 0, 0), new DateTime(1999, 3, 10, 9, 0, 0), new DateTime(2001, 1, 10, 9, 0, 0),new DateTime(2001, 2, 10, 9, 0, 0), new DateTime(2001, 3, 10, 9, 0, 0), new DateTime(2003, 1, 10, 9, 0, 0),new DateTime(2003, 2, 10, 9, 0, 0), new DateTime(2003, 3, 10, 9, 0, 0), }, dates); //test 3 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Interval = 3, Count = 10, ByYearDay = new int[] { 1, 100, 200 } }; dates = r1.GetDates(new DateTime(1997, 1, 1, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 1, 1, 9, 0, 0),new DateTime(1997, 4, 10, 9, 0, 0),new DateTime(1997, 7, 19, 9, 0, 0), new DateTime(2000, 1, 1, 9, 0, 0),new DateTime(2000, 4, 9, 9, 0, 0),new DateTime(2000, 7, 18, 9, 0, 0), new DateTime(2003, 1, 1, 9, 0, 0),new DateTime(2003, 4, 10, 9, 0, 0),new DateTime(2003, 7, 19, 9, 0, 0), new DateTime(2006, 1, 1, 9, 0, 0) }, dates); //test 4 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Count = 3, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("20MO") } }; dates = r1.GetDates(new DateTime(1997, 5, 19, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 5, 19, 9, 0, 0),new DateTime(1998, 5, 18, 9, 0, 0),new DateTime(1999, 5, 17, 9, 0, 0) }, dates); //test 5 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Count = 3, ByWeekNo = new int[]{20}, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("MO") } }; dates = r1.GetDates(new DateTime(1997, 5, 12, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 5, 12, 9, 0, 0),new DateTime(1998, 5, 11, 9, 0, 0),new DateTime(1999, 5, 17, 9, 0, 0) }, dates); //test 6 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Count = 11, ByMonth = new int[] { 3 }, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("TH") } }; dates = r1.GetDates(new DateTime(1997, 3, 13, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 3, 13, 9, 0, 0), new DateTime(1997, 3, 20, 9, 0, 0),new DateTime(1997, 3, 27, 9, 0, 0), new DateTime(1998, 3, 5, 9, 0, 0), new DateTime(1998, 3, 12, 9, 0, 0),new DateTime(1998, 3, 19, 9, 0, 0),new DateTime(1998, 3, 26, 9, 0, 0), new DateTime(1999, 3, 4, 9, 0, 0),new DateTime(1999, 3, 11, 9, 0, 0),new DateTime(1999, 3, 18, 9, 0, 0),new DateTime(1999, 3, 25, 9, 0, 0) }, dates); //test 7 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Count = 13, ByMonth = new int[] { 6,7,8 }, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("TH") } }; dates = r1.GetDates(new DateTime(1997, 6, 5, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 6, 5, 9, 0, 0), new DateTime(1997, 6, 12, 9, 0, 0),new DateTime(1997, 6, 19, 9, 0, 0),new DateTime(1997, 6, 26, 9, 0, 0), new DateTime(1997, 7, 3, 9, 0, 0), new DateTime(1997, 7, 10, 9, 0, 0),new DateTime(1997, 7, 17, 9, 0, 0),new DateTime(1997, 7, 24, 9, 0, 0),new DateTime(1997, 7, 31, 9, 0, 0), new DateTime(1997, 8, 7, 9, 0, 0), new DateTime(1997, 8, 14, 9, 0, 0),new DateTime(1997, 8, 21, 9, 0, 0),new DateTime(1997, 8, 28, 9, 0, 0) }, dates); //test 8 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Interval = 4, Count = 3, ByMonth = new int[] { 11 }, ByMonthDay = new int[] { 2,3,4,5,6,7,8 }, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("TU") } }; dates = r1.GetDates(new DateTime(1996, 11, 5, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1996, 11, 5, 9, 0, 0), new DateTime(2000, 11, 7, 9, 0, 0), new DateTime(2004, 11, 2, 9, 0, 0) }, dates); //friday 13 r1 = new RecurrenceRule() { Freq = Frequency.Yearly, Until = new DateTime(2013,1,1), ByMonthDay = new int[] { 13 }, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("fr") } }; dates = r1.GetDates(new DateTime(2012, 1, 1, 0, 0, 0), _fromDate, new DateTime(2014, 1, 1, 0, 0, 0)); } [TestMethod] public void MonthlyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Monthly, Count = 10, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("1FR") } }; var dates = r1.GetDates(new DateTime(1997, 9, 5, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 5, 9, 0, 0), new DateTime(1997, 10, 3, 9, 0, 0), new DateTime(1997, 11, 7, 9, 0, 0),new DateTime(1997, 12, 5, 9, 0, 0), new DateTime(1998, 1, 2, 9, 0, 0),new DateTime(1998, 2, 6, 9, 0, 0), new DateTime(1998, 3, 6, 9, 0, 0),new DateTime(1998, 4, 3, 9, 0, 0), new DateTime(1998, 5, 1, 9, 0, 0), new DateTime(1998, 6, 5, 9, 0, 0)}, dates); //test 2 r1 = new RecurrenceRule() { Freq = Frequency.Monthly, Until = new DateTime(1997, 12, 24), ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("1FR") } }; dates = r1.GetDates(new DateTime(1997, 9, 5, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 5, 9, 0, 0), new DateTime(1997, 10, 3, 9, 0, 0), new DateTime(1997, 11, 7, 9, 0, 0),new DateTime(1997, 12, 5, 9, 0, 0)}, dates); //test 3 r1 = new RecurrenceRule() { Freq = Frequency.Monthly, Count = 10, Interval = 2, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("1SU"), RecurrenceRule.WeekDay.Parse("-1SU") } }; dates = r1.GetDates(new DateTime(1997, 9, 7, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 7, 9, 0, 0), new DateTime(1997, 9, 28, 9, 0, 0), new DateTime(1997, 11, 2, 9, 0, 0),new DateTime(1997, 11, 30, 9, 0, 0), new DateTime(1998, 1, 4, 9, 0, 0),new DateTime(1998, 1, 25, 9, 0, 0), new DateTime(1998, 3, 1, 9, 0, 0),new DateTime(1998, 3, 29, 9, 0, 0), new DateTime(1998, 5, 3, 9, 0, 0),new DateTime(1998, 5, 31, 9, 0, 0) }, dates); //test 4 r1 = new RecurrenceRule() { Freq = Frequency.Monthly, Count = 6, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("-2MO")} }; dates = r1.GetDates(new DateTime(1997, 9, 22, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 22, 9, 0, 0), new DateTime(1997, 10, 20, 9, 0, 0), new DateTime(1997, 11, 17, 9, 0, 0),new DateTime(1997, 12, 22, 9, 0, 0), new DateTime(1998, 1, 19, 9, 0, 0),new DateTime(1998, 2, 16, 9, 0, 0) }, dates); //test 5 r1 = new RecurrenceRule() { Freq = Frequency.Monthly, Interval = 18, Count = 10, ByMonthDay = new int[] {10,11,12,13,14,15 } }; dates = r1.GetDates(new DateTime(1997, 9, 10, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 10, 9, 0, 0), new DateTime(1997, 9, 11, 9, 0, 0), new DateTime(1997, 9, 12, 9, 0, 0),new DateTime(1997, 9, 13, 9, 0, 0), new DateTime(1997, 9, 14, 9, 0, 0),new DateTime(1997, 9, 15, 9, 0, 0), new DateTime(1999, 3, 10, 9, 0, 0),new DateTime(1999, 3, 11, 9, 0, 0), new DateTime(1999, 3, 12, 9, 0, 0),new DateTime(1999, 3, 13, 9, 0, 0) }, dates); } [TestMethod] public void WeeklyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Weekly, Count = 10 }; var dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 9, 9, 0, 0), new DateTime(1997, 9, 16, 9, 0, 0),new DateTime(1997, 9, 23, 9, 0, 0), new DateTime(1997, 9, 30, 9, 0, 0),new DateTime(1997, 10, 7, 9, 0, 0), new DateTime(1997, 10, 14, 9, 0, 0),new DateTime(1997, 10, 21, 9, 0, 0), new DateTime(1997, 10, 28, 9, 0, 0), new DateTime(1997, 11, 4, 9, 0, 0)}, dates); //test 2 r1 = new RecurrenceRule() { Freq = Frequency.Weekly, Interval = 2, WKST = RecurrenceRule.WeekDay.Parse("su"), Count = 10 }; dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 16, 9, 0, 0), new DateTime(1997, 9, 30, 9, 0, 0),new DateTime(1997, 10, 14, 9, 0, 0), new DateTime(1997, 10, 28, 9, 0, 0),new DateTime(1997, 11, 11, 9, 0, 0), new DateTime(1997, 11, 25, 9, 0, 0),new DateTime(1997, 12, 9, 9, 0, 0), new DateTime(1997, 12, 23, 9, 0, 0), new DateTime(1998, 1, 6, 9, 0, 0)}, dates); //test 3 r1 = new RecurrenceRule() { Freq = Frequency.Weekly, Interval = 2, WKST = RecurrenceRule.WeekDay.Parse("su"), Count = 8, ByDay = new RecurrenceRule.WeekDay[] { RecurrenceRule.WeekDay.Parse("tu"), RecurrenceRule.WeekDay.Parse("th") } }; dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 4, 9, 0, 0), new DateTime(1997, 9, 16, 9, 0, 0),new DateTime(1997, 9, 18, 9, 0, 0), new DateTime(1997, 9, 30, 9, 0, 0),new DateTime(1997, 10, 2, 9, 0, 0), new DateTime(1997, 10, 14, 9, 0, 0),new DateTime(1997, 10, 16, 9, 0, 0)}, dates); r1 = RecurrenceRule.Parse("freq=weekly;count=3;interval=2;byday=mo"); dates = r1.GetDates(new DateTime(2012, 1, 2, 0, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(2012, 1, 2, 0, 0, 0), new DateTime(2012, 1, 16, 0, 0, 0), new DateTime(2012, 1, 30, 0, 0, 0)}, dates); } [TestMethod] public void DailyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Daily, Count = 5, Interval = 10 }; var dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 12, 9, 0, 0), new DateTime(1997, 9, 22, 9, 0, 0),new DateTime(1997, 10, 2, 9, 0, 0), new DateTime(1997, 10, 12, 9, 0, 0)}, dates); } [TestMethod] public void HorlyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Hourly, Until = new DateTime(1997,9,2,17,0,0), Interval = 3 }; var dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 2, 12, 0, 0), new DateTime(1997, 9, 2, 15, 0, 0)}, dates); } [TestMethod] public void MinutelyRules() { //test 1 var r1 = new RecurrenceRule() { Freq = Frequency.Minutely, ByHour = new int[]{9,10,11,12,13,14,15,16}, Count = 5, Interval = 20 }; var dates = r1.GetDates(new DateTime(1997, 9, 2, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 2, 9, 0, 0), new DateTime(1997, 9, 2, 9, 20, 0), new DateTime(1997, 9, 2, 9, 40, 0),new DateTime(1997, 9, 2, 10, 0, 0),new DateTime(1997, 9, 2, 10, 20, 0)}, dates); } [TestMethod] public void BySetPosRules() { //test 1 var r1 = RecurrenceRule.Parse("FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-2;count=7"); var dates = r1.GetDates(new DateTime(1997, 9, 29, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 29, 9, 0, 0), new DateTime(1997, 10, 30, 9, 0, 0), new DateTime(1997, 11, 27, 9, 0, 0),new DateTime(1997, 12, 30, 9, 0, 0),new DateTime(1998, 1, 29, 9, 0, 0), new DateTime(1998, 2, 26, 9, 0, 0),new DateTime(1998, 3, 30, 9, 0, 0)}, dates); //test 2 r1 = RecurrenceRule.Parse("FREQ=MONTHLY;COUNT=3;BYDAY=TU,WE,TH;BYSETPOS=3"); dates = r1.GetDates(new DateTime(1997, 9, 4, 9, 0, 0), _fromDate, _toDate); CollectionAssert.AreEqual(new List<DateTime>(){ new DateTime(1997, 9, 4, 9, 0, 0), new DateTime(1997, 10, 7, 9, 0, 0), new DateTime(1997, 11, 6, 9, 0, 0)}, dates); } [TestMethod] public void ParseFromStringTest() { //tets var r1 = RecurrenceRule.Parse("FREQ=WEEKLY;INTERVAL=2;UNTIL=19971224T000000Z;WKST=SU"); Assert.AreEqual( new DateTime(1997, 12, 24, 0, 0, 0),r1.Until); } } }
// 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Document : TextDocument { private WeakReference<SemanticModel> _model; private Task<SyntaxTree> _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state) { } private DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind { get { return DocumentState.SourceCodeKind; } } /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree(out SyntaxTree syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default(VersionStamp); if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) { return DocumentState.TryGetTopLevelChangeTextVersion(out version); } /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default(CancellationToken)) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <code>false</code> then these methods will return <code>null</code> instead. /// </summary> public bool SupportsSyntaxTree { get { return DocumentState.SupportsSyntaxTree; } } /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <code>false</code> then this method will return <code>null</code> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> public Task<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken = default(CancellationToken)) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Default<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { return _syntaxTreeResultTask; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); return _syntaxTreeResultTask; } // do it async for real. return DocumentState.GetSyntaxTreeAsync(cancellationToken); } internal SyntaxTree GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot(out SyntaxNode root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> public async Task<SyntaxNode> GetSyntaxRootAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (!this.SupportsSyntaxTree) { return null; } var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken); return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel(out SemanticModel semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> public async Task<SemanticModel> GetSemanticModelAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // it looks like someone has set it. try to reuse same semantic model if (original.TryGetTarget(out semanticModel)) { return semanticModel; } // it looks like cache is gone. reset the cache. original.SetTarget(result); return result; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) { return this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) { return this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) { return this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes IList<TextChange> textChanges = null; if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language).ToImmutableArray(); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal async Task<Document> WithFrozenPartialSemanticsAsync(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = await this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(this.Id, cancellationToken).ConfigureAwait(false); return newSolution.GetDocument(this.Id); } else { return this; } } private string GetDebuggerDisplay() { return this.Name; } private AsyncLazy<DocumentOptionSet> _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_cachedOptions == null) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var optionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, Project.Solution.Options, c).ConfigureAwait(false); return new DocumentOptionSet(optionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } return _cachedOptions.GetValueAsync(cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class DistinctTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 0, 9999, 0, 888, -1, 66, -1, -777, 1, 2, -12345, 66, 66, -1, -1 } where x > Int32.MinValue select x; Assert.Equal(q.Distinct(), q.Distinct()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "Calling Twice", "SoS" } where String.IsNullOrEmpty(x) select x; Assert.Equal(q.Distinct(), q.Distinct()); } [Fact] public void EmptySource() { int[] source = { }; Assert.Empty(source.Distinct()); } [Fact] public void SingleNullElementExplicitlyUseDefaultComparer() { string[] source = { null }; string[] expected = { null }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void EmptyStringDistinctFromNull() { string[] source = { null, null, string.Empty }; string[] expected = { null, string.Empty }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void CollapsDuplicateNulls() { string[] source = { null, null }; string[] expected = { null }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void SourceAllDuplicates() { int[] source = { 5, 5, 5, 5, 5, 5 }; int[] expected = { 5 }; Assert.Equal(expected, source.Distinct()); } [Fact] public void AllUnique() { int[] source = { 2, -5, 0, 6, 10, 9 }; Assert.Equal(source, source.Distinct()); } [Fact] public void SomeDuplicatesIncludingNulls() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; int?[] expected = { 1, 2, null }; Assert.Equal(expected, source.Distinct()); } [Fact] public void LastSameAsFirst() { int[] source = { 1, 2, 3, 4, 5, 1 }; int[] expected = { 1, 2, 3, 4, 5 }; Assert.Equal(expected, source.Distinct()); } // Multiple elements repeat non-consecutively [Fact] public void RepeatsNonConsecutive() { int[] source = { 1, 1, 2, 2, 4, 3, 1, 3, 2 }; int[] expected = { 1, 2, 4, 3 }; Assert.Equal(expected, source.Distinct()); } [Fact] public void NullComparer() { string[] source = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; string[] expected = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; Assert.Equal(expected, source.Distinct()); } [Fact] public void NullSource() { string[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.Distinct()); } [Fact] public void NullSourceCustomComparer() { string[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.Distinct(StringComparer.Ordinal)); } [Fact] public void CustomEqualityComparer() { string[] source = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; string[] expected = { "Bob", "Tim", "Robert" }; Assert.Equal(expected, source.Distinct(new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Theory, MemberData(nameof(SequencesWithDuplicates))] public void FindDistinctAndValidate<T>(T unusedArgumentToForceTypeInference, IEnumerable<T> original) { // Convert to list to avoid repeated enumerations of the enumerables. var originalList = original.ToList(); var distinctList = originalList.Distinct().ToList(); // Ensure the result doesn't contain duplicates. var hashSet = new HashSet<T>(); foreach (var i in distinctList) Assert.True(hashSet.Add(i)); var originalSet = new HashSet<T>(original); Assert.Superset(originalSet, hashSet); Assert.Subset(originalSet, hashSet); } public static IEnumerable<object[]> SequencesWithDuplicates() { // Validate an array of different numeric data types. yield return new object[] { 0, new int[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0L, new long[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0F, new float[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0.0, new double[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0M, new decimal[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; // Try strings yield return new object[] { "", new [] { "add", "add", "subtract", "multiply", "divide", "divide2", "subtract", "add", "power", "exponent", "hello", "class", "namespace", "namespace", "namespace", } }; } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Distinct(); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ToArray() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; int?[] expected = { 1, 2, null }; Assert.Equal(expected, source.Distinct().ToArray()); } [Fact] public void ToList() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; int?[] expected = { 1, 2, null }; Assert.Equal(expected, source.Distinct().ToList()); } [Fact] public void Count() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; Assert.Equal(3, source.Distinct().Count()); } [Fact] public void RepeatEnumerating() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; var result = source.Distinct(); Assert.Equal(result, result); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Net; using Azure.Data.Tables.Sas; using NUnit.Framework; namespace Azure.Data.Tables.Test { public class TableUriBuilderTests { [Test] public void TableUriBuilder_RegularUrl_AccountTest() { // Arrange var uriString = "https://account.core.table.windows.net?comp=list"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("comp=list", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_TableTest() { // Arrange var uriString = "https://account.core.table.windows.net/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_PortTest() { // Arrange var uriString = "https://account.core.table.windows.net:8080/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(8080, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_SasTest() { // Arrange var uriString = "https://account.core.table.windows.net/table?tn=table&sv=2015-04-05&spr=https&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sip=168.1.5.60-168.1.5.70&sr=b&sp=rw&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual(new DateTimeOffset(2015, 4, 30, 2, 23, 26, TimeSpan.Zero), tableuribuilder.Sas.ExpiresOn); Assert.AreEqual("", tableuribuilder.Sas.Identifier); Assert.AreEqual(TableSasIPRange.Parse("168.1.5.60-168.1.5.70"), tableuribuilder.Sas.IPRange); Assert.AreEqual("rw", tableuribuilder.Sas.Permissions); Assert.AreEqual(TableSasProtocol.Https, tableuribuilder.Sas.Protocol); Assert.AreEqual("b", tableuribuilder.Sas.Resource); Assert.IsNull(tableuribuilder.Sas.ResourceTypes); Assert.AreEqual("Z/RHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk=", tableuribuilder.Sas.Signature); Assert.AreEqual(new DateTimeOffset(2015, 4, 29, 22, 18, 26, TimeSpan.Zero), tableuribuilder.Sas.StartsOn); Assert.AreEqual("2015-04-05", tableuribuilder.Sas.Version); Assert.AreEqual("", tableuribuilder.Query); Assert.That(newUri.ToString(), Is.EqualTo(originalUri.Uri.ToString())); } [Test] public void TableUriBuilder_IPStyleUrl_AccountTest() { // Arrange var uriString = "https://127.0.0.1/account?comp=list"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("comp=list", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_TableTest() { // Arrange var uriString = "https://127.0.0.1/account/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_PortTest() { // Arrange var uriString = "https://127.0.0.1:8080/account/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(8080, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_AccountOnlyTest() { // Arrange var uriString = "https://127.0.0.1/account"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_SasTest() { // Arrange var uriString = "https://127.0.0.1/account/table?tn=table&sv=2015-04-05&spr=https&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sip=168.1.5.60-168.1.5.70&sr=b&sp=rw&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.AreEqual(new DateTimeOffset(2015, 4, 30, 2, 23, 26, TimeSpan.Zero), tableuribuilder.Sas.ExpiresOn); Assert.AreEqual("", tableuribuilder.Sas.Identifier); Assert.AreEqual(TableSasIPRange.Parse("168.1.5.60-168.1.5.70"), tableuribuilder.Sas.IPRange); Assert.AreEqual("rw", tableuribuilder.Sas.Permissions); Assert.AreEqual(TableSasProtocol.Https, tableuribuilder.Sas.Protocol); Assert.AreEqual("b", tableuribuilder.Sas.Resource); Assert.IsNull(tableuribuilder.Sas.ResourceTypes); Assert.AreEqual("Z/RHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk=", tableuribuilder.Sas.Signature); Assert.AreEqual(new DateTimeOffset(2015, 4, 29, 22, 18, 26, TimeSpan.Zero), tableuribuilder.Sas.StartsOn); Assert.AreEqual("2015-04-05", tableuribuilder.Sas.Version); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] [TestCase("2020-10-27", "2020-10-28")] [TestCase("2020-10-27T12:10Z", "2020-10-28T13:20Z")] [TestCase("2020-10-27T12:10:11Z", "2020-10-28T13:20:14Z")] [TestCase("2020-10-27T12:10:11.1234567Z", "2020-10-28T13:20:14.7654321Z")] public void TableBuilder_SasStartExpiryTimeFormats(string startTime, string expiryTime) { // Arrange Uri initialUri = new Uri($"https://account.table.core.windows.net/table?tn=tablename&sv=2020-04-08&st={WebUtility.UrlEncode(startTime)}&se={WebUtility.UrlEncode(expiryTime)}&sr=b&sp=racwd&sig=jQetX8odiJoZ7Yo0X8vWgh%2FMqRv9WE3GU%2Fr%2BLNMK3GU%3D"); TableUriBuilder tableuribuilder = new TableUriBuilder(initialUri); // Act Uri resultUri = tableuribuilder.ToUri(); // Assert Assert.That(resultUri.ToString(), Is.EqualTo(initialUri.ToString())); Assert.IsTrue(resultUri.PathAndQuery.Contains($"st={WebUtility.UrlEncode(startTime)}")); Assert.IsTrue(resultUri.PathAndQuery.Contains($"se={WebUtility.UrlEncode(expiryTime)}")); } [Test] public void TableUriBuilder_SasInvalidStartExpiryTimeFormat() { // Arrange string startTime = "2020-10-27T12Z"; string expiryTime = "2020-10-28T13Z"; Uri initialUri = new Uri($"https://account.table.core.windows.net/table?sv=2020-04-08&st={WebUtility.UrlEncode(startTime)}&se={WebUtility.UrlEncode(expiryTime)}&sr=b&sp=racwd&sig=jQetX8odiJoZ7Yo0X8vWgh%2FMqRv9WE3GU%2Fr%2BLNMK3GU%3D"); // Act try { new TableUriBuilder(initialUri); } catch (FormatException e) { Assert.IsTrue(e.Message.Contains("was not recognized as a valid DateTime.")); } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SPCrossDomainLibraryDemoWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Copyright (c) .NET Foundation and contributors. 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.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Configurer; using Microsoft.Extensions.EnvironmentAbstractions; using System.Text.Json; using System.Text.Json.Serialization; using NuGet.Frameworks; using NuGet.Versioning; namespace Microsoft.DotNet.ToolPackage { internal class LocalToolsResolverCache : ILocalToolsResolverCache { private readonly DirectoryPath _cacheVersionedDirectory; private readonly IFileSystem _fileSystem; private const int LocalToolResolverCacheVersion = 1; public LocalToolsResolverCache(IFileSystem fileSystem = null, DirectoryPath? cacheDirectory = null, int version = LocalToolResolverCacheVersion) { _fileSystem = fileSystem ?? new FileSystemWrapper(); DirectoryPath appliedCacheDirectory = cacheDirectory ?? new DirectoryPath(Path.Combine(CliFolderPathCalculator.ToolsResolverCachePath)); _cacheVersionedDirectory = appliedCacheDirectory.WithSubDirectories(version.ToString()); } public void Save( IDictionary<RestoredCommandIdentifier, RestoredCommand> restoredCommandMap) { EnsureFileStorageExists(); foreach (var distinctPackageIdAndRestoredCommandMap in restoredCommandMap.GroupBy(x => x.Key.PackageId)) { PackageId distinctPackageId = distinctPackageIdAndRestoredCommandMap.Key; string packageCacheFile = GetCacheFile(distinctPackageId); if (_fileSystem.File.Exists(packageCacheFile)) { var existingCacheTable = GetCacheTable(packageCacheFile); var diffedRow = distinctPackageIdAndRestoredCommandMap .Where(pair => !TryGetMatchingRestoredCommand( pair.Key, existingCacheTable, out _)) .Select(pair => ConvertToCacheRow(pair.Key, pair.Value)); _fileSystem.File.WriteAllText( packageCacheFile, JsonSerializer.ToString(existingCacheTable.Concat(diffedRow))); } else { var rowsToAdd = distinctPackageIdAndRestoredCommandMap .Select(mapWithSamePackageId => ConvertToCacheRow( mapWithSamePackageId.Key, mapWithSamePackageId.Value)); _fileSystem.File.WriteAllText( packageCacheFile, JsonSerializer.ToString(rowsToAdd)); } } } public bool TryLoad( RestoredCommandIdentifier restoredCommandIdentifier, out RestoredCommand restoredCommand) { string packageCacheFile = GetCacheFile(restoredCommandIdentifier.PackageId); if (_fileSystem.File.Exists(packageCacheFile)) { if (TryGetMatchingRestoredCommand( restoredCommandIdentifier, GetCacheTable(packageCacheFile), out restoredCommand)) { return true; } } restoredCommand = null; return false; } private CacheRow[] GetCacheTable(string packageCacheFile) { CacheRow[] cacheTable = Array.Empty<CacheRow>(); try { cacheTable = JsonSerializer.Parse<CacheRow[]>(_fileSystem.File.ReadAllText(packageCacheFile)); } catch (JsonReaderException) { // if file is corrupted, treat it as empty since it is not the source of truth } return cacheTable; } public bool TryLoadHighestVersion( RestoredCommandIdentifierVersionRange query, out RestoredCommand restoredCommandList) { restoredCommandList = null; string packageCacheFile = GetCacheFile(query.PackageId); if (_fileSystem.File.Exists(packageCacheFile)) { var list = GetCacheTable(packageCacheFile) .Select(c => Convert(query.PackageId, c)) .Where(strongTypeStored => query.VersionRange.Satisfies(strongTypeStored.restoredCommandIdentifier.Version)) .Where(onlyVersionSatisfies => onlyVersionSatisfies.restoredCommandIdentifier == query.WithVersion(onlyVersionSatisfies.restoredCommandIdentifier.Version)) .OrderByDescending(allMatched => allMatched.restoredCommandIdentifier.Version) .FirstOrDefault(); if (!list.restoredCommand.Equals(default(RestoredCommand))) { restoredCommandList = list.restoredCommand; return true; } } return false; } private string GetCacheFile(PackageId packageId) { return _cacheVersionedDirectory.WithFile(packageId.ToString()).Value; } private void EnsureFileStorageExists() { _fileSystem.Directory.CreateDirectory(_cacheVersionedDirectory.Value); } private static CacheRow ConvertToCacheRow( RestoredCommandIdentifier restoredCommandIdentifier, RestoredCommand restoredCommandList) { return new CacheRow { Version = restoredCommandIdentifier.Version.ToNormalizedString(), TargetFramework = restoredCommandIdentifier.TargetFramework.GetShortFolderName(), RuntimeIdentifier = restoredCommandIdentifier.RuntimeIdentifier.ToLowerInvariant(), Name = restoredCommandIdentifier.CommandName.Value, Runner = restoredCommandList.Runner, PathToExecutable = restoredCommandList.Executable.Value }; } private static (RestoredCommandIdentifier restoredCommandIdentifier, RestoredCommand restoredCommand) Convert( PackageId packageId, CacheRow cacheRow) { RestoredCommandIdentifier restoredCommandIdentifier = new RestoredCommandIdentifier( packageId, NuGetVersion.Parse(cacheRow.Version), NuGetFramework.Parse(cacheRow.TargetFramework), cacheRow.RuntimeIdentifier, new ToolCommandName(cacheRow.Name)); RestoredCommand restoredCommand = new RestoredCommand( new ToolCommandName(cacheRow.Name), cacheRow.Runner, new FilePath(cacheRow.PathToExecutable)); return (restoredCommandIdentifier, restoredCommand); } private static bool TryGetMatchingRestoredCommand( RestoredCommandIdentifier restoredCommandIdentifier, CacheRow[] cacheTable, out RestoredCommand restoredCommandList) { (RestoredCommandIdentifier restoredCommandIdentifier, RestoredCommand restoredCommand)[] matchingRow = cacheTable .Select(c => Convert(restoredCommandIdentifier.PackageId, c)) .Where(candidate => candidate.restoredCommandIdentifier == restoredCommandIdentifier).ToArray(); if (matchingRow.Length >= 2) { throw new ResolverCacheInconsistentException( $"more than one row for {restoredCommandIdentifier.DebugToString()}"); } if (matchingRow.Length == 1) { restoredCommandList = matchingRow[0].restoredCommand; return true; } restoredCommandList = null; return false; } private class CacheRow { public string Version { get; set; } public string TargetFramework { get; set; } public string RuntimeIdentifier { get; set; } public string Name { get; set; } public string Runner { get; set; } public string PathToExecutable { get; set; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Infrastructure { using System.Data.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Resources; using System.Data.Entity.TestDoubles; using System.Linq; using System.Threading; using System.Threading.Tasks; using Moq; using Moq.Protected; using Xunit; using MockHelper = System.Data.Entity.Core.Objects.MockHelper; public class CommitFailureHandlerTests { public class Initialize : TestBase { [Fact] public void Initializes_with_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = CreateCommitFailureHandlerMock().Object) { handler.Initialize(context); Assert.Same(context, handler.ObjectContext); Assert.Same(context.InterceptionContext.DbContexts.FirstOrDefault(), handler.DbContext); Assert.Same(((EntityConnection)context.Connection).StoreConnection, handler.Connection); Assert.Same(((EntityConnection)context.Connection).StoreConnection, handler.Connection); Assert.IsType<TransactionContext>(handler.TransactionContext); } var context = new DbContext("c"); using (var handler = CreateCommitFailureHandlerMock().Object) { handler.Initialize(context, context.Database.Connection); Assert.Null(handler.ObjectContext); Assert.Same(context, handler.DbContext); Assert.Same(context.Database.Connection, handler.Connection); Assert.IsType<TransactionContext>(handler.TransactionContext); } } [Fact] public void Initializes_with_DbContext() { var context = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(context, context.Database.Connection); Assert.Null(handler.ObjectContext); Assert.Same(context, handler.DbContext); Assert.Same(context.Database.Connection, handler.Connection); Assert.IsType<TransactionContext>(handler.TransactionContext); } } [Fact] public void Throws_for_null_parameters() { using (var handler = new CommitFailureHandler()) { Assert.Equal( "connection", Assert.Throws<ArgumentNullException>(() => handler.Initialize(new DbContext("c"), null)).ParamName); Assert.Equal( "context", Assert.Throws<ArgumentNullException>(() => handler.Initialize(null, new Mock<DbConnection>().Object)).ParamName); Assert.Equal( "context", Assert.Throws<ArgumentNullException>(() => handler.Initialize(null)).ParamName); } } [Fact] public void Throws_if_already_initialized_with_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(context)).Message); var dbContext = new DbContext("c"); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(dbContext, dbContext.Database.Connection)).Message); } } [Fact] public void Throws_if_already_initialized_with_DbContext() { var dbContext = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(dbContext, dbContext.Database.Connection); var context = MockHelper.CreateMockObjectContext<object>(); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(context)).Message); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(dbContext, dbContext.Database.Connection)).Message); } } } public class Dispose : TestBase { [Fact] public void Removes_interceptor() { var mockConnection = new Mock<DbConnection>().Object; var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; using (handlerMock.Object) { DbInterception.Dispatch.Connection.Close(mockConnection, new DbInterceptionContext()); handlerMock.Verify(m => m.Closed(It.IsAny<DbConnection>(), It.IsAny<DbConnectionInterceptionContext>()), Times.Once()); handlerMock.Object.Dispose(); DbInterception.Dispatch.Connection.Close(mockConnection, new DbInterceptionContext()); handlerMock.Verify(m => m.Closed(It.IsAny<DbConnection>(), It.IsAny<DbConnectionInterceptionContext>()), Times.Once()); } } [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.Dispose(); commitFailureHandlerMock.Protected().Verify("Dispose", Times.Once(), true); } } [Fact] public void Can_be_invoked_twice_without_throwing() { var handler = new CommitFailureHandler(); handler.Dispose(); handler.Dispose(); } } public class MatchesParentContext : TestBase { [Fact] public void Throws_for_null_parameters() { using (var handler = new CommitFailureHandler()) { Assert.Equal( "connection", Assert.Throws<ArgumentNullException>(() => handler.MatchesParentContext(null, new DbInterceptionContext())) .ParamName); Assert.Equal( "interceptionContext", Assert.Throws<ArgumentNullException>(() => handler.MatchesParentContext(new Mock<DbConnection>().Object, null)) .ParamName); } } [Fact] public void Returns_false_with_DbContext_if_nothing_matches() { using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), CreateMockConnection()); Assert.False( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_false_with_DbContext_if_different_context_same_connection() { var connection = CreateMockConnection(); using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), connection); Assert.False( handler.MatchesParentContext( connection, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_DbContext_if_same_context() { var context = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(context, CreateMockConnection()); Assert.True( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(context))); } } [Fact] public void Returns_true_with_DbContext_if_no_context_same_connection() { var connection = CreateMockConnection(); using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), connection); Assert.True( handler.MatchesParentContext( connection, new DbInterceptionContext())); } } [Fact] public void Returns_false_with_ObjectContext_if_nothing_matches() { using (var handler = new CommitFailureHandler()) { handler.Initialize(MockHelper.CreateMockObjectContext<object>()); Assert.False( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_false_with_ObjectContext_if_different_context_same_connection() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.False( handler.MatchesParentContext( ((EntityConnection)context.Connection).StoreConnection, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_ObjectContext_if_same_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.True( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(context) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_ObjectContext_if_no_context_same_connection() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.True( handler.MatchesParentContext( ((EntityConnection)context.Connection).StoreConnection, new DbInterceptionContext())); } } } public class PruneTransactionHistory : TestBase { [Fact] public void Delegates_to_protected_method() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup("PruneTransactionHistory", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>()).Callback(() => { }); using (var handler = handlerMock.Object) { handler.PruneTransactionHistory(); handlerMock.Protected().Verify("PruneTransactionHistory", Times.Once(), true, true); } } } #if !NET40 public class PruneTransactionHistoryAsync : TestBase { [Fact] public void Delegates_to_protected_method() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); using (var handler = handlerMock.Object) { handler.PruneTransactionHistoryAsync().Wait(); handlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, CancellationToken.None); } } [Fact] public void Delegates_to_protected_method_with_CancelationToken() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); using (var handler = handlerMock.Object) { var token = new CancellationToken(); handler.PruneTransactionHistoryAsync(token).Wait(); handlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, token); } } } #endif public class ClearTransactionHistory : TestBase { [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.ClearTransactionHistory(); commitFailureHandlerMock.Protected().Verify("PruneTransactionHistory", Times.Once(), true, true); } } } #if !NET40 public class ClearTransactionHistoryAsync : TestBase { [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.ClearTransactionHistoryAsync().Wait(); commitFailureHandlerMock.Protected() .Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, CancellationToken.None); } } [Fact] public void Delegates_to_protected_method_with_CancelationToken() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { var token = new CancellationToken(); handler.ClearTransactionHistoryAsync(token).Wait(); commitFailureHandlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, token); } } } #endif public class BeganTransaction { [Fact] public void BeganTransaction_does_not_fail_if_exception_thrown_such_that_there_is_no_transaction() { var context = MockHelper.CreateMockObjectContext<object>(); var handler = new CommitFailureHandler(); handler.Initialize(context); var interceptionContext = new BeginTransactionInterceptionContext().WithObjectContext(context); Assert.DoesNotThrow(() => handler.BeganTransaction(new Mock<DbConnection>().Object, interceptionContext)); } } private static DbConnection CreateMockConnection() { var connectionMock = new Mock<DbConnection>(); connectionMock.Protected() .Setup<DbProviderFactory>("DbProviderFactory") .Returns(GenericProviderFactory<DbProviderFactory>.Instance); return connectionMock.Object; } private static Mock<CommitFailureHandler> CreateCommitFailureHandlerMock() { Func<DbConnection, TransactionContext> transactionContextFactory = c => { var transactionContextMock = new Mock<TransactionContext>(c) { CallBase = true }; var transactionRowSet = new InMemoryDbSet<TransactionRow>(); transactionContextMock.Setup(m => m.Transactions).Returns(transactionRowSet); return transactionContextMock.Object; }; var handlerMock = new Mock<CommitFailureHandler>(transactionContextFactory) { CallBase = true }; handlerMock.Protected().Setup("PruneTransactionHistory", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>()).Callback(() => { }); #if !NET40 handlerMock.Protected() .Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); #endif return handlerMock; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// Currently active AudioEvents along with their AudioSource components for instance limiting events /// </summary> public class ActiveEvent : IDisposable { private AudioSource primarySource = null; public AudioSource PrimarySource { get { return primarySource; } private set { primarySource = value; if (primarySource != null) { primarySource.enabled = true; } } } private AudioSource secondarySource = null; public AudioSource SecondarySource { get { return secondarySource; } private set { secondarySource = value; if (secondarySource != null) { secondarySource.enabled = true; } } } public bool IsPlaying { get { return (primarySource != null && primarySource.isPlaying) || (secondarySource != null && secondarySource.isPlaying); } } public GameObject AudioEmitter { get; private set; } public string MessageOnAudioEnd { get; private set; } public AudioEvent audioEvent = null; public bool isStoppable = true; public float volDest = 1; public float altVolDest = 1; public float currentFade = 0; public bool playingAlt = false; public bool isActiveTimeComplete = false; public float activeTime = 0; public bool cancelEvent = false; public ActiveEvent(AudioEvent audioEvent, GameObject emitter, AudioSource primarySource, AudioSource secondarySource, string messageOnAudioEnd = null) { this.audioEvent = audioEvent; AudioEmitter = emitter; PrimarySource = primarySource; SecondarySource = secondarySource; MessageOnAudioEnd = messageOnAudioEnd; SetSourceProperties(); } public static AnimationCurve SpatialRolloff; /// <summary> /// Set the volume, spatialization, etc., on our AudioSources to match the settings on the event to play. /// </summary> private void SetSourceProperties() { Action<Action<AudioSource>> forEachSource = (action) => { action(PrimarySource); if (SecondarySource != null) { action(SecondarySource); } }; AudioEvent audioEvent = this.audioEvent; switch (audioEvent.Spatialization) { case SpatialPositioningType.TwoD: forEachSource((source) => { source.spatialBlend = 0f; source.spatialize = false; }); break; case SpatialPositioningType.ThreeD: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = false; }); break; case SpatialPositioningType.SpatialSound: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = true; }); break; default: Debug.LogErrorFormat("Unexpected spatialization type: {0}", audioEvent.Spatialization.ToString()); break; } if (audioEvent.Spatialization == SpatialPositioningType.SpatialSound) { CreateFlatSpatialRolloffCurve(); forEachSource((source) => { source.rolloffMode = AudioRolloffMode.Custom; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, SpatialRolloff); SpatialSoundSettings.SetRoomSize(source, audioEvent.RoomSize); SpatialSoundSettings.SetMinGain(source, audioEvent.MinGain); SpatialSoundSettings.SetMaxGain(source, audioEvent.MaxGain); SpatialSoundSettings.SetUnityGainDistance(source, audioEvent.UnityGainDistance); }); } else { forEachSource((source) => { if (audioEvent.Spatialization == SpatialPositioningType.ThreeD) { source.rolloffMode = AudioRolloffMode.Custom; source.maxDistance = audioEvent.MaxDistanceAttenuation3D; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.AttenuationCurve); source.SetCustomCurve(AudioSourceCurveType.SpatialBlend, audioEvent.SpatialCurve); source.SetCustomCurve(AudioSourceCurveType.Spread, audioEvent.SpreadCurve); source.SetCustomCurve(AudioSourceCurveType.ReverbZoneMix, audioEvent.ReverbCurve); } else { source.rolloffMode = AudioRolloffMode.Logarithmic; } }); } if (audioEvent.Bus != null) { forEachSource((source) => source.outputAudioMixerGroup = audioEvent.Bus); } float pitch = 1f; if (audioEvent.PitchRandomization != 0) { pitch = UnityEngine.Random.Range(audioEvent.PitchCenter - audioEvent.PitchRandomization, audioEvent.PitchCenter + audioEvent.PitchRandomization); } else { pitch = audioEvent.PitchCenter; } forEachSource((source) => source.pitch = pitch); float vol = 1f; if (audioEvent.FadeInTime > 0) { forEachSource((source) => source.volume = 0f); this.currentFade = audioEvent.FadeInTime; if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } this.volDest = vol; } else { if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } forEachSource((source) => source.volume = vol); } float pan = audioEvent.PanCenter; if (audioEvent.PanRandomization != 0) { pan = UnityEngine.Random.Range(audioEvent.PanCenter - audioEvent.PanRandomization, audioEvent.PanCenter + audioEvent.PanRandomization); } forEachSource((source) => source.panStereo = pan); } /// <summary> /// Sets the pitch value for the primary source. /// </summary> /// <param name="newPitch">The value to set the pitch, between 0 (exclusive) and 3 (inclusive).</param> public void SetPitch(float newPitch) { if (newPitch <= 0 || newPitch > 3) { Debug.LogErrorFormat("Invalid pitch {0} set for event", newPitch); return; } this.PrimarySource.pitch = newPitch; } public void Dispose() { if (this.primarySource != null) { this.primarySource.enabled = false; this.primarySource = null; } if (this.secondarySource != null) { this.secondarySource.enabled = false; this.secondarySource = null; } } /// <summary> /// Creates a flat animation curve to negate Unity's distance attenuation when using Spatial Sound /// </summary> public static void CreateFlatSpatialRolloffCurve() { if (SpatialRolloff != null) { return; } SpatialRolloff = new AnimationCurve(); SpatialRolloff.AddKey(0, 1); SpatialRolloff.AddKey(1, 1); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** ** ** ** Purpose: Holds state about A/G/R permissionsets in a callstack or appdomain ** (Replacement for PermissionListSet) ** =============================================================================*/ namespace System.Security { using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; [Serializable] sealed internal class PermissionListSet { // Only internal (public) methods are creation methods and demand evaluation methods. // Scroll down to the end to see them. private PermissionSetTriple m_firstPermSetTriple; private ArrayList m_permSetTriples; #if FEATURE_COMPRESSEDSTACK private ArrayList m_zoneList; private ArrayList m_originList; #endif // FEATURE_COMPRESSEDSTACK internal PermissionListSet() {} private void EnsureTriplesListCreated() { if (m_permSetTriples == null) { m_permSetTriples = new ArrayList(); if (m_firstPermSetTriple != null) { m_permSetTriples.Add(m_firstPermSetTriple); m_firstPermSetTriple = null; } } } #if FEATURE_PLS [System.Security.SecurityCritical] // auto-generated internal void UpdateDomainPLS (PermissionListSet adPLS) { if (adPLS != null && adPLS.m_firstPermSetTriple != null) UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet); } [System.Security.SecurityCritical] // auto-generated internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) { Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null"); if (m_firstPermSetTriple == null) m_firstPermSetTriple = new PermissionSetTriple(); // update the grant and denied sets m_firstPermSetTriple.UpdateGrant(grantSet); m_firstPermSetTriple.UpdateRefused(deniedSet); } #endif // FEATURE_PLS private void Terminate(PermissionSetTriple currentTriple) { UpdateTripleListAndCreateNewTriple(currentTriple, null); } [System.Security.SecurityCritical] // auto-generated private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls) { #if FEATURE_COMPRESSEDSTACK this.UpdateZoneAndOrigin(pls); #endif // FEATURE_COMPRESSEDSTACK this.UpdatePermissions(currentTriple, pls); this.UpdateTripleListAndCreateNewTriple(currentTriple, null); } [System.Security.SecurityCritical] // auto-generated private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls) { #if FEATURE_COMPRESSEDSTACK this.UpdateZoneAndOrigin(pls); #endif // FEATURE_COMPRESSEDSTACK return this.UpdatePermissions(currentTriple, pls); } [System.Security.SecurityCritical] // auto-generated private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd) { #if FEATURE_COMPRESSEDSTACK FrameSecurityDescriptorWithResolver fsdWithResolver = fsd as FrameSecurityDescriptorWithResolver; if (fsdWithResolver != null) { return Update2(currentTriple, fsdWithResolver); } #endif // FEATURE_COMPRESSEDSTACK // check imperative bool fHalt = Update2(currentTriple, fsd, false); if (!fHalt) { // then declarative fHalt = Update2(currentTriple, fsd, true); } return fHalt; } #if FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver) { System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver; CompressedStack dynamicCompressedStack = resolver.GetSecurityContext(); dynamicCompressedStack.CompleteConstruction(null); return this.Update(currentTriple, dynamicCompressedStack.PLS); } #endif // FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] // auto-generated private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative) { // Deny PermissionSet deniedPset = fsd.GetDenials(fDeclarative); if (deniedPset != null) { currentTriple.UpdateRefused(deniedPset); } // permit only PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative); if (permitOnlyPset != null) { currentTriple.UpdateGrant(permitOnlyPset); } // Assert all possible if (fsd.GetAssertAllPossible()) { // If we have no grant set, it means that the only assembly we've seen on the stack so // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the // compressed stack is also FullTrust. if (currentTriple.GrantSet == null) currentTriple.GrantSet = PermissionSet.s_fullTrust; UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); currentTriple.GrantSet = PermissionSet.s_fullTrust; currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative)); return true; } // Assert PermissionSet assertPset = fsd.GetAssertions(fDeclarative); if (assertPset != null) { if (assertPset.IsUnrestricted()) { // If we have no grant set, it means that the only assembly we've seen on the stack so // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the // compressed stack is also FullTrust. if (currentTriple.GrantSet == null) currentTriple.GrantSet = PermissionSet.s_fullTrust; UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); currentTriple.GrantSet = PermissionSet.s_fullTrust; currentTriple.UpdateAssert(assertPset); return true; } PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset); if (retTriple != null) { EnsureTriplesListCreated(); m_permSetTriples.Add(retTriple); } } return false; } [System.Security.SecurityCritical] // auto-generated private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r) { #if FEATURE_COMPRESSEDSTACK ZoneIdentityPermission z; UrlIdentityPermission u; currentTriple.UpdateGrant(in_g, out z, out u); currentTriple.UpdateRefused(in_r); AppendZoneOrigin(z, u); #else // !FEATURE_COMPRESEDSTACK currentTriple.UpdateGrant(in_g); currentTriple.UpdateRefused(in_r); #endif // FEATURE_COMPRESSEDSTACK } // Called from the VM for HG CS construction [System.Security.SecurityCritical] // auto-generated private void Update(PermissionSet in_g) { if (m_firstPermSetTriple == null) m_firstPermSetTriple = new PermissionSetTriple(); Update(m_firstPermSetTriple, in_g, null); } #if FEATURE_COMPRESSEDSTACK private void UpdateZoneAndOrigin(PermissionListSet pls) { if (pls != null) { if (this.m_zoneList == null && pls.m_zoneList != null && pls.m_zoneList.Count > 0) this.m_zoneList = new ArrayList(); UpdateArrayList(this.m_zoneList, pls.m_zoneList); if (this.m_originList == null && pls.m_originList != null && pls.m_originList.Count > 0) this.m_originList = new ArrayList(); UpdateArrayList(this.m_originList, pls.m_originList); } } #endif // FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] // auto-generated private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls) { if (pls != null) { if (pls.m_permSetTriples != null) { // DCS has an AGR List. So we need to add the AGR List UpdateTripleListAndCreateNewTriple(currentTriple,pls.m_permSetTriples); } else { // Common case: One AGR set PermissionSetTriple tmp_psTriple = pls.m_firstPermSetTriple; PermissionSetTriple retTriple; // First try and update currentTriple. Return value indicates if we can stop construction if (currentTriple.Update(tmp_psTriple, out retTriple)) return true; // If we got a non-null retTriple, what it means is that compression failed, // and we now have 2 triples to deal with: retTriple and currentTriple. // retTriple has to be appended first. then currentTriple. if (retTriple != null) { EnsureTriplesListCreated(); // we just created a new triple...add the previous one (returned) to the list m_permSetTriples.Add(retTriple); } } } else { // pls can be null only outside the loop in CreateCompressedState UpdateTripleListAndCreateNewTriple(currentTriple, null); } return false; } private void UpdateTripleListAndCreateNewTriple(PermissionSetTriple currentTriple, ArrayList tripleList) { if (!currentTriple.IsEmpty()) { if (m_firstPermSetTriple == null && m_permSetTriples == null) { m_firstPermSetTriple = new PermissionSetTriple(currentTriple); } else { EnsureTriplesListCreated(); m_permSetTriples.Add(new PermissionSetTriple(currentTriple)); } currentTriple.Reset(); } if (tripleList != null) { EnsureTriplesListCreated(); m_permSetTriples.AddRange(tripleList); } } private static void UpdateArrayList(ArrayList current, ArrayList newList) { if (newList == null) return; for(int i=0;i < newList.Count; i++) { if (!current.Contains(newList[i])) current.Add(newList[i]); } } #if FEATURE_COMPRESSEDSTACK private void AppendZoneOrigin(ZoneIdentityPermission z, UrlIdentityPermission u) { if (z != null) { if (m_zoneList == null) m_zoneList = new ArrayList(); z.AppendZones(m_zoneList); } if (u != null) { if (m_originList == null) m_originList = new ArrayList(); u.AppendOrigin(m_originList); } } [System.Security.SecurityCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] // public(internal) interface begins... // Creation functions static internal PermissionListSet CreateCompressedState(CompressedStack cs, CompressedStack innerCS) { // function that completes the construction of the compressed stack if not done so already (bottom half for demand evaluation) bool bHaltConstruction = false; if (cs.CompressedStackHandle == null) return null; // FT case or Security off PermissionListSet pls = new PermissionListSet(); PermissionSetTriple currentTriple = new PermissionSetTriple(); int numDomains = CompressedStack.GetDCSCount(cs.CompressedStackHandle); for (int i=numDomains-1; (i >= 0 && !bHaltConstruction) ; i--) { DomainCompressedStack dcs = CompressedStack.GetDomainCompressedStack(cs.CompressedStackHandle, i); if (dcs == null) continue; // we hit a FT Domain if (dcs.PLS == null) { // We failed on some DCS throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"))); } pls.UpdateZoneAndOrigin(dcs.PLS); pls.Update(currentTriple, dcs.PLS); bHaltConstruction = dcs.ConstructionHalted; } if (!bHaltConstruction) { PermissionListSet tmp_pls = null; // Construction did not halt. if (innerCS != null) { innerCS.CompleteConstruction(null); tmp_pls = innerCS.PLS; } pls.Terminate(currentTriple, tmp_pls); } else { pls.Terminate(currentTriple); } return pls; } [System.Security.SecurityCritical] // auto-generated static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction) { PermissionListSet pls = new PermissionListSet(); PermissionSetTriple currentTriple = new PermissionSetTriple(); PermissionSet tmp_g, tmp_r; // Construct the descriptor list int descCount = DomainCompressedStack.GetDescCount(unmanagedDCS); bHaltConstruction = false; for(int i=0; (i < descCount && !bHaltConstruction); i++) { FrameSecurityDescriptor fsd; Assembly assembly; if (DomainCompressedStack.GetDescriptorInfo(unmanagedDCS, i, out tmp_g, out tmp_r, out assembly, out fsd)) { // Got an FSD bHaltConstruction = pls.Update(currentTriple, fsd); } else { pls.Update(currentTriple, tmp_g, tmp_r); } } if (!bHaltConstruction) { // domain if (!DomainCompressedStack.IgnoreDomain(unmanagedDCS)) { DomainCompressedStack.GetDomainPermissionSets(unmanagedDCS, out tmp_g, out tmp_r); pls.Update(currentTriple, tmp_g, tmp_r); } } pls.Terminate(currentTriple); // return the created object return pls; } [System.Security.SecurityCritical] // auto-generated static internal PermissionListSet CreateCompressedState_HG() { PermissionListSet pls = new PermissionListSet(); CompressedStack.GetHomogeneousPLS(pls); return pls; } #endif // #if FEATURE_COMPRESSEDSTACK // Private Demand evaluation functions - only called from the VM [System.Security.SecurityCritical] // auto-generated internal bool CheckDemandNoThrow(CodeAccessPermission demand) { // AppDomain permissions - no asserts. So there should only be one triple to work with Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); PermissionToken permToken = null; if (demand != null) permToken = PermissionToken.GetToken(demand); return m_firstPermSetTriple.CheckDemandNoThrow(demand, permToken); } [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemandNoThrow(PermissionSet pSet) { // AppDomain permissions - no asserts. So there should only be one triple to work with Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet); } // Demand evauation functions [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; if (m_permSetTriples != null) { for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) { PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; bRet = psTriple.CheckDemand(demand, permToken, rmh); } } else if (m_firstPermSetTriple != null) { bRet = m_firstPermSetTriple.CheckDemand(demand, permToken, rmh); } return bRet; } [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh) { PermissionSet unused; CheckSetDemandWithModification(pset, out unused, rmh); return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk } [System.Security.SecurityCritical] internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; PermissionSet demandSet = pset; alteredDemandSet = null; if (m_permSetTriples != null) { for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) { PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; bRet = psTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); if (alteredDemandSet != null) demandSet = alteredDemandSet; } } else if (m_firstPermSetTriple != null) { bRet = m_firstPermSetTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); } return bRet; } /// <summary> /// Check to see if the PLS satisfies a demand for the special permissions encoded in flags /// </summary> /// <param name="flags">set of flags to check (See PermissionType)</param> [System.Security.SecurityCritical] // auto-generated private bool CheckFlags(int flags) { Contract.Assert(flags != 0, "Invalid permission flag demand"); bool check = true; if (m_permSetTriples != null) { for (int i = 0; i < m_permSetTriples.Count && check && flags != 0; i++) { check &= ((PermissionSetTriple)m_permSetTriples[i]).CheckFlags(ref flags); } } else if (m_firstPermSetTriple != null) { check = m_firstPermSetTriple.CheckFlags(ref flags); } return check; } /// <summary> /// Demand which succeeds if either a set of special permissions or a permission set is granted /// to the call stack /// </summary> /// <param name="flags">set of flags to check (See PermissionType)</param> /// <param name="grantSet">alternate permission set to check</param> [System.Security.SecurityCritical] // auto-generated internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet) { if (CheckFlags(flags)) return; CheckSetDemand(grantSet, RuntimeMethodHandleInternal.EmptyHandle); } #if FEATURE_COMPRESSEDSTACK internal void GetZoneAndOrigin(ArrayList zoneList, ArrayList originList, PermissionToken zoneToken, PermissionToken originToken) { if (m_zoneList != null) zoneList.AddRange(m_zoneList); if (m_originList != null) originList.AddRange(m_originList); } #endif } }
//---------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security.Tokens; sealed class InitiatorSessionSymmetricMessageSecurityProtocol : MessageSecurityProtocol, IInitiatorSecuritySessionProtocol { SecurityToken outgoingSessionToken; SecurityTokenAuthenticator sessionTokenAuthenticator; List<SecurityToken> incomingSessionTokens; DerivedKeySecurityToken derivedSignatureToken; DerivedKeySecurityToken derivedEncryptionToken; SecurityStandardsManager sessionStandardsManager; bool requireDerivedKeys; Object thisLock = new Object(); bool returnCorrelationState = false; public InitiatorSessionSymmetricMessageSecurityProtocol(SessionSymmetricMessageSecurityProtocolFactory factory, EndpointAddress target, Uri via) : base(factory, target, via) { if (factory.ActAsInitiator != true) { Fx.Assert("This protocol can only be used at the initiator."); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ProtocolMustBeInitiator, "InitiatorSessionSymmetricMessageSecurityProtocol"))); } this.requireDerivedKeys = factory.SecurityTokenParameters.RequireDerivedKeys; if (requireDerivedKeys) { SecurityTokenSerializer innerTokenSerializer = this.Factory.StandardsManager.SecurityTokenSerializer; WSSecureConversation secureConversation = (innerTokenSerializer is WSSecurityTokenSerializer) ? ((WSSecurityTokenSerializer)innerTokenSerializer).SecureConversation : new WSSecurityTokenSerializer(this.Factory.MessageSecurityVersion.SecurityVersion).SecureConversation; this.sessionStandardsManager = new SecurityStandardsManager(factory.MessageSecurityVersion, new DerivedKeyCachingSecurityTokenSerializer(2, true, secureConversation, innerTokenSerializer)); } } Object ThisLock { get { return thisLock; } } protected override bool PerformIncomingAndOutgoingMessageExpectationChecks { get { return false; } } public bool ReturnCorrelationState { get { return this.returnCorrelationState; } set { this.returnCorrelationState = value; } } SessionSymmetricMessageSecurityProtocolFactory Factory { get { return (SessionSymmetricMessageSecurityProtocolFactory)base.MessageSecurityProtocolFactory; } } public SecurityToken GetOutgoingSessionToken() { lock (ThisLock) { return this.outgoingSessionToken; } } public void SetIdentityCheckAuthenticator(SecurityTokenAuthenticator authenticator) { this.sessionTokenAuthenticator = authenticator; } public void SetOutgoingSessionToken(SecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } lock (ThisLock) { this.outgoingSessionToken = token; if (this.requireDerivedKeys) { string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(this.sessionStandardsManager.MessageSecurityVersion.SecureConversationVersion); this.derivedSignatureToken = new DerivedKeySecurityToken(-1, 0, this.Factory.OutgoingAlgorithmSuite.GetSignatureKeyDerivationLength(token, this.sessionStandardsManager.MessageSecurityVersion.SecureConversationVersion), null, DerivedKeySecurityToken.DefaultNonceLength, token, this.Factory.SecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal), derivationAlgorithm, SecurityUtils.GenerateId()); this.derivedEncryptionToken = new DerivedKeySecurityToken(-1, 0, this.Factory.OutgoingAlgorithmSuite.GetEncryptionKeyDerivationLength(token, this.sessionStandardsManager.MessageSecurityVersion.SecureConversationVersion), null, DerivedKeySecurityToken.DefaultNonceLength, token, this.Factory.SecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal), derivationAlgorithm, SecurityUtils.GenerateId()); } } } public List<SecurityToken> GetIncomingSessionTokens() { lock (ThisLock) { return this.incomingSessionTokens; } } public void SetIncomingSessionTokens(List<SecurityToken> tokens) { if (tokens == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokens"); } lock (ThisLock) { this.incomingSessionTokens = new List<SecurityToken>(tokens); } } void GetTokensForOutgoingMessages(out SecurityToken signingToken, out SecurityToken encryptionToken, out SecurityToken sourceToken, out SecurityTokenParameters tokenParameters) { lock (ThisLock) { if (this.requireDerivedKeys) { signingToken = this.derivedSignatureToken; encryptionToken = this.derivedEncryptionToken; sourceToken = this.outgoingSessionToken; } else { signingToken = encryptionToken = this.outgoingSessionToken; sourceToken = null; } } if (this.Factory.ApplyConfidentiality) { EnsureOutgoingIdentity(sourceToken ?? encryptionToken, this.sessionTokenAuthenticator); } tokenParameters = this.Factory.GetTokenParameters(); } protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state) { SecurityToken signingToken; SecurityToken encryptionToken; SecurityToken sourceToken; SecurityTokenParameters tokenParameters; this.GetTokensForOutgoingMessages(out signingToken, out encryptionToken, out sourceToken, out tokenParameters); IList<SupportingTokenSpecification> supportingTokens; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (TryGetSupportingTokens(this.Factory, this.Target, this.Via, message, timeoutHelper.RemainingTime(), false, out supportingTokens)) { SecurityProtocolCorrelationState newCorrelationState = CreateCorrelationStateIfRequired(); SetUpDelayedSecurityExecution(ref message, signingToken, encryptionToken, sourceToken, tokenParameters, supportingTokens, newCorrelationState); return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, newCorrelationState, callback, state); } else { return new SecureOutgoingMessageAsyncResult(message, this, signingToken, encryptionToken, sourceToken, tokenParameters, timeoutHelper.RemainingTime(), callback, state); } } internal SecurityProtocolCorrelationState CreateCorrelationStateIfRequired() { if (this.ReturnCorrelationState) { return new SecurityProtocolCorrelationState(null); } else { return null; } } protected override SecurityProtocolCorrelationState SecureOutgoingMessageCore(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState) { SecurityToken signingToken; SecurityToken encryptionToken; SecurityToken sourceToken; SecurityTokenParameters tokenParameters; this.GetTokensForOutgoingMessages(out signingToken, out encryptionToken, out sourceToken, out tokenParameters); SecurityProtocolCorrelationState newCorrelationState = CreateCorrelationStateIfRequired(); IList<SupportingTokenSpecification> supportingTokens; this.TryGetSupportingTokens(this.SecurityProtocolFactory, this.Target, this.Via, message, timeout, true, out supportingTokens); SetUpDelayedSecurityExecution(ref message, signingToken, encryptionToken, sourceToken, tokenParameters, supportingTokens, newCorrelationState); return newCorrelationState; } protected override void EndSecureOutgoingMessageCore(IAsyncResult result, out Message message, out SecurityProtocolCorrelationState newCorrelationState) { if (result is CompletedAsyncResult<Message, SecurityProtocolCorrelationState>) { message = CompletedAsyncResult<Message, SecurityProtocolCorrelationState>.End(result, out newCorrelationState); } else { message = SecureOutgoingMessageAsyncResult.End(result, out newCorrelationState); } } internal void SetUpDelayedSecurityExecution(ref Message message, SecurityToken signingToken, SecurityToken encryptionToken, SecurityToken sourceToken, SecurityTokenParameters tokenParameters, IList<SupportingTokenSpecification> supportingTokens, SecurityProtocolCorrelationState correlationState) { SessionSymmetricMessageSecurityProtocolFactory factory = this.Factory; string actor = string.Empty; SendSecurityHeader securityHeader = ConfigureSendSecurityHeader(message, actor, supportingTokens, correlationState); if (sourceToken != null) { securityHeader.AddPrerequisiteToken(sourceToken); } if (this.Factory.ApplyIntegrity) { securityHeader.SetSigningToken(signingToken, tokenParameters); } if (Factory.ApplyConfidentiality) { securityHeader.SetEncryptionToken(encryptionToken, tokenParameters); } message = securityHeader.SetupExecution(); } protected override SecurityProtocolCorrelationState VerifyIncomingMessageCore(ref Message message, string actor, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates) { SessionSymmetricMessageSecurityProtocolFactory factory = this.Factory; IList<SupportingTokenAuthenticatorSpecification> dummyAuthenticators; ReceiveSecurityHeader securityHeader = ConfigureReceiveSecurityHeader(message, string.Empty, correlationStates, this.requireDerivedKeys ? this.sessionStandardsManager : null, out dummyAuthenticators); List<SecurityToken> sessionTokens = GetIncomingSessionTokens(); securityHeader.ConfigureSymmetricBindingClientReceiveHeader(sessionTokens, this.Factory.SecurityTokenParameters); // do not enforce the key derivation requirement for CancelResponse due to WSE interop securityHeader.EnforceDerivedKeyRequirement = (message.Headers.Action != factory.StandardsManager.SecureConversationDriver.CloseResponseAction.Value); ProcessSecurityHeader(securityHeader, ref message, null, timeout, correlationStates); SecurityToken signingToken = securityHeader.SignatureToken; // verify that the signing token was one of the session tokens bool isSessionToken = false; for (int i = 0; i < sessionTokens.Count; ++i) { if (Object.ReferenceEquals(signingToken, sessionTokens[i])) { isSessionToken = true; break; } } if (!isSessionToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.NoSessionTokenPresentInMessage))); } if (factory.RequireIntegrity) { ReadOnlyCollection<IAuthorizationPolicy> signingTokenPolicies = this.sessionTokenAuthenticator.ValidateToken(signingToken); DoIdentityCheckAndAttachInitiatorSecurityProperty(message, signingToken, signingTokenPolicies); } return null; } sealed class SecureOutgoingMessageAsyncResult : GetSupportingTokensAsyncResult { Message message; InitiatorSessionSymmetricMessageSecurityProtocol binding; SecurityToken signingToken; SecurityToken encryptionToken; SecurityToken sourceToken; SecurityTokenParameters tokenParameters; SecurityProtocolCorrelationState newCorrelationState; public SecureOutgoingMessageAsyncResult(Message message, InitiatorSessionSymmetricMessageSecurityProtocol binding, SecurityToken signingToken, SecurityToken encryptionToken, SecurityToken sourceToken, SecurityTokenParameters tokenParameters, TimeSpan timeout, AsyncCallback callback, object state) : base(message, binding, timeout, callback, state) { this.message = message; this.binding = binding; this.signingToken = signingToken; this.encryptionToken = encryptionToken; this.sourceToken = sourceToken; this.tokenParameters = tokenParameters; this.Start(); } protected override bool OnGetSupportingTokensDone(TimeSpan timeout) { newCorrelationState = binding.CreateCorrelationStateIfRequired(); binding.SetUpDelayedSecurityExecution(ref message, signingToken, encryptionToken, sourceToken, tokenParameters, this.SupportingTokens, newCorrelationState); return true; } internal static Message End(IAsyncResult result, out SecurityProtocolCorrelationState newCorrelationState) { SecureOutgoingMessageAsyncResult self = AsyncResult.End<SecureOutgoingMessageAsyncResult>(result); newCorrelationState = self.newCorrelationState; return self.message; } } } }
//----------------------------------------------------------------------- // <copyright file="FileSourceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Akka.Actor; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public class FileSourceSpec : AkkaSpec { private readonly string _testText; private readonly ActorMaterializer _materializer; private readonly FileInfo _testFilePath = new FileInfo(Path.Combine(Path.GetTempPath(), "file-source-spec.tmp")); private FileInfo _manyLinesPath; public FileSourceSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher"); _materializer = Sys.Materializer(settings); var sb = new StringBuilder(6000); foreach (var character in new[] { "a", "b", "c", "d", "e", "f" }) for (var i = 0; i < 1000; i++) sb.Append(character); _testText = sb.ToString(); } [Fact] public void FileSource_should_read_contents_from_a_file() { this.AssertAllStagesStopped(() => { var chunkSize = 512; var bufferAttributes = Attributes.CreateInputBuffer(1, 2); var p = FileIO.FromFile(TestFile(), chunkSize) .WithAttributes(bufferAttributes) .RunWith(Sink.AsPublisher<ByteString>(false), _materializer); var c = this.CreateManualSubscriberProbe<ByteString>(); p.Subscribe(c); var sub = c.ExpectSubscription(); var remaining = _testText; var nextChunk = new Func<string>(() => { string chunks; if (remaining.Length <= chunkSize) { chunks = remaining; remaining = string.Empty; } else { chunks = remaining.Substring(0, chunkSize); remaining = remaining.Substring(chunkSize); } return chunks; }); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); sub.Request(200); var expectedChunk = nextChunk(); while (!string.IsNullOrEmpty(expectedChunk)) { var actual = c.ExpectNext().DecodeString(Encoding.UTF8); actual.Should().Be(expectedChunk); expectedChunk = nextChunk(); } sub.Request(1); c.ExpectComplete(); }, _materializer); } [Fact] public void FileSource_should_complete_only_when_all_contents_of_a_file_have_been_signalled() { this.AssertAllStagesStopped(() => { var chunkSize = 512; var bufferAttributes = Attributes.CreateInputBuffer(1, 2); var demandAllButOnechunks = _testText.Length / chunkSize - 1; var p = FileIO.FromFile(TestFile(), chunkSize) .WithAttributes(bufferAttributes) .RunWith(Sink.AsPublisher<ByteString>(false), _materializer); var c = this.CreateManualSubscriberProbe<ByteString>(); p.Subscribe(c); var sub = c.ExpectSubscription(); var remaining = _testText; var nextChunk = new Func<string>(() => { string chunks; if (remaining.Length <= chunkSize) { chunks = remaining; remaining = string.Empty; } else { chunks = remaining.Substring(0, chunkSize); remaining = remaining.Substring(chunkSize); } return chunks; }); sub.Request(demandAllButOnechunks); for (var i = 0; i < demandAllButOnechunks; i++) c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectComplete(); }, _materializer); } [Fact] public void FileSource_should_onError_with_failure_and_return_a_failed_IOResult_when_trying_to_read_from_file_which_does_not_exist() { this.AssertAllStagesStopped(() => { var t = FileIO.FromFile(NotExistingFile()) .ToMaterialized(Sink.AsPublisher<ByteString>(false), Keep.Both) .Run(_materializer); var r = t.Item1; var p = t.Item2; var c = this.CreateManualSubscriberProbe<ByteString>(); p.Subscribe(c); c.ExpectSubscription(); c.ExpectError(); r.AwaitResult(Dilated(TimeSpan.FromSeconds(3))).WasSuccessful.ShouldBeFalse(); }, _materializer); } [Theory] [InlineData(512, 2)] [InlineData(512, 4)] [InlineData(2048, 2)] [InlineData(2048, 4)] public void FileSource_should_count_lines_in_a_real_file(int chunkSize, int readAhead) { var s = FileIO.FromFile(ManyLines(), chunkSize) .WithAttributes(Attributes.CreateInputBuffer(readAhead, readAhead)); var f = s.RunWith( Sink.Aggregate<ByteString, int>(0, (acc, l) => acc + l.DecodeString(Encoding.UTF8).Count(c => c == '\n')), _materializer); f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var lineCount = f.Result; lineCount.Should().Be(LinesCount); } [Fact] public void FileSource_should_use_dedicated_blocking_io_dispatcher_by_default() { this.AssertAllStagesStopped(() => { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = sys.Materializer(); try { var p = FileIO.FromFile(ManyLines()).RunWith(this.SinkProbe<ByteString>(), materializer); (materializer as ActorMaterializerImpl).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>().Refs.First(r => r.Path.ToString().Contains("fileSource")); try { Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher"); } finally { p.Cancel(); } } finally { Shutdown(sys); } }, _materializer); } [Fact(Skip = "overriding dispatcher should be made available with dispatcher alias support in materializer (#17929)")] //FIXME: overriding dispatcher should be made available with dispatcher alias support in materializer (#17929) public void FileSource_should_should_allow_overriding_the_dispather_using_Attributes() { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = sys.Materializer(); try { var p = FileIO.FromFile(ManyLines()) .WithAttributes(ActorAttributes.CreateDispatcher("akka.actor.default-dispatcher")) .RunWith(this.SinkProbe<ByteString>(), materializer); (materializer as ActorMaterializerImpl).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>().Refs.First(r => r.Path.ToString().Contains("File")); try { Utils.AssertDispatcher(actorRef, "akka.actor.default-dispatcher"); } finally { p.Cancel(); } } finally { Shutdown(sys); } } [Fact] public void FileSource_should_not_signal_OnComplete_more_than_once() { FileIO.FromFile(TestFile(), 2*_testText.Length) .RunWith(this.SinkProbe<ByteString>(), _materializer) .RequestNext(ByteString.FromString(_testText)) .ExpectComplete() .ExpectNoMsg(TimeSpan.FromSeconds(1)); } private int LinesCount { get; } = 2000 + new Random().Next(300); private FileInfo ManyLines() { _manyLinesPath = new FileInfo(Path.Combine(Path.GetTempPath(), $"file-source-spec-lines_{LinesCount}.tmp")); var line = ""; var lines = new List<string>(); for (var i = 0; i < LinesCount; i++) line += "a"; for (var i = 0; i < LinesCount; i++) lines.Add(line); File.AppendAllLines(_manyLinesPath.FullName, lines); return _manyLinesPath; } private FileInfo TestFile() { File.AppendAllText(_testFilePath.FullName, _testText); return _testFilePath; } private FileInfo NotExistingFile() { var f = new FileInfo(Path.Combine(Path.GetTempPath(), "not-existing-file.tmp")); if (f.Exists) f.Delete(); return f; } protected override void AfterAll() { base.AfterAll(); //give the system enough time to shutdown and release the file handle Thread.Sleep(500); _manyLinesPath?.Delete(); _testFilePath?.Delete(); } } }
// 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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExprFactory { private GlobalSymbolContext _globalSymbolContext; private ConstValFactory _constants; public ExprFactory(GlobalSymbolContext globalSymbolContext) { Debug.Assert(globalSymbolContext != null); _globalSymbolContext = globalSymbolContext; _constants = new ConstValFactory(); } public ConstValFactory GetExprConstants() { return _constants; } private TypeManager GetTypes() { return _globalSymbolContext.GetTypes(); } private BSYMMGR GetGlobalSymbols() { return _globalSymbolContext.GetGlobalSymbols(); } public EXPRCALL CreateCall(EXPRFLAG nFlags, CType pType, EXPR pOptionalArguments, EXPRMEMGRP pMemberGroup, MethWithInst MWI) { Debug.Assert(0 == (nFlags & ~( EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_CONSTRAINED | EXPRFLAG.EXF_BASECALL | EXPRFLAG.EXF_NEWSTRUCTASSG | EXPRFLAG.EXF_IMPLICITSTRUCTASSG | EXPRFLAG.EXF_MASK_ANY ) )); EXPRCALL rval = new EXPRCALL(); rval.kind = ExpressionKind.EK_CALL; rval.type = pType; rval.flags = nFlags; rval.SetOptionalArguments(pOptionalArguments); rval.SetMemberGroup(pMemberGroup); rval.nubLiftKind = NullableCallLiftKind.NotLifted; rval.castOfNonLiftedResultToLiftedType = null; rval.mwi = MWI; Debug.Assert(rval != null); return (rval); } public EXPRFIELD CreateField(EXPRFLAG nFlags, CType pType, EXPR pOptionalObject, uint nOffset, FieldWithType FWT, EXPR pOptionalLHS) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MEMBERSET | EXPRFLAG.EXF_MASK_ANY))); EXPRFIELD rval = new EXPRFIELD(); rval.kind = ExpressionKind.EK_FIELD; rval.type = pType; rval.flags = nFlags; rval.SetOptionalObject(pOptionalObject); if (FWT != null) { rval.fwt = FWT; } Debug.Assert(rval != null); return (rval); } public EXPRFUNCPTR CreateFunctionPointer(EXPRFLAG nFlags, CType pType, EXPR pObject, MethWithInst MWI) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_BASECALL))); EXPRFUNCPTR rval = new EXPRFUNCPTR(); rval.kind = ExpressionKind.EK_FUNCPTR; rval.type = pType; rval.flags = nFlags; rval.OptionalObject = pObject; rval.mwi = new MethWithInst(MWI); Debug.Assert(rval != null); return (rval); } public EXPRARRINIT CreateArrayInit(EXPRFLAG nFlags, CType pType, EXPR pOptionalArguments, EXPR pOptionalArgumentDimensions, int[] pDimSizes) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY | EXPRFLAG.EXF_ARRAYCONST | EXPRFLAG.EXF_ARRAYALLCONST))); EXPRARRINIT rval = new EXPRARRINIT(); rval.kind = ExpressionKind.EK_ARRINIT; rval.type = pType; rval.SetOptionalArguments(pOptionalArguments); rval.SetOptionalArgumentDimensions(pOptionalArgumentDimensions); rval.dimSizes = pDimSizes; rval.dimSize = pDimSizes != null ? pDimSizes.Length : 0; Debug.Assert(rval != null); return (rval); } public EXPRPROP CreateProperty(CType pType, EXPR pOptionalObject) { MethPropWithInst mwi = new MethPropWithInst(); EXPRMEMGRP pMemGroup = CreateMemGroup(pOptionalObject, mwi); return CreateProperty(pType, null, null, pMemGroup, null, null, null); } public EXPRPROP CreateProperty(CType pType, EXPR pOptionalObjectThrough, EXPR pOptionalArguments, EXPRMEMGRP pMemberGroup, PropWithType pwtSlot, MethWithType mwtGet, MethWithType mwtSet) { EXPRPROP rval = new EXPRPROP(); rval.kind = ExpressionKind.EK_PROP; rval.type = pType; rval.flags = 0; rval.SetOptionalObjectThrough(pOptionalObjectThrough); rval.SetOptionalArguments(pOptionalArguments); rval.SetMemberGroup(pMemberGroup); if (pwtSlot != null) { rval.pwtSlot = pwtSlot; } if (mwtSet != null) { rval.mwtSet = mwtSet; } Debug.Assert(rval != null); return (rval); } public EXPREVENT CreateEvent(CType pType, EXPR pOptionalObject, EventWithType EWT) { EXPREVENT rval = new EXPREVENT(); rval.kind = ExpressionKind.EK_EVENT; rval.type = pType; rval.flags = 0; rval.OptionalObject = pOptionalObject; if (EWT != null) { rval.ewt = EWT; } Debug.Assert(rval != null); return (rval); } public EXPRMEMGRP CreateMemGroup(EXPRFLAG nFlags, Name pName, TypeArray pTypeArgs, SYMKIND symKind, CType pTypePar, MethodOrPropertySymbol pMPS, EXPR pObject, CMemberLookupResults memberLookupResults) { Debug.Assert(0 == (nFlags & ~( EXPRFLAG.EXF_CTOR | EXPRFLAG.EXF_INDEXER | EXPRFLAG.EXF_OPERATOR | EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_BASECALL | EXPRFLAG.EXF_DELEGATE | EXPRFLAG.EXF_USERCALLABLE | EXPRFLAG.EXF_MASK_ANY ) )); EXPRMEMGRP rval = new EXPRMEMGRP(); rval.kind = ExpressionKind.EK_MEMGRP; rval.type = GetTypes().GetMethGrpType(); rval.flags = nFlags; rval.name = pName; rval.typeArgs = pTypeArgs; rval.sk = symKind; rval.SetParentType(pTypePar); rval.SetOptionalObject(pObject); rval.SetMemberLookupResults(memberLookupResults); rval.SetOptionalLHS(null); if (rval.typeArgs == null) { rval.typeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(rval != null); return (rval); } public EXPRMEMGRP CreateMemGroup( EXPR pObject, MethPropWithInst mwi) { Name pName = mwi.Sym != null ? mwi.Sym.name : null; MethodOrPropertySymbol methProp = mwi.MethProp(); CType pType = mwi.GetType(); if (pType == null) { pType = GetTypes().GetErrorSym(); } return CreateMemGroup(0, pName, mwi.TypeArgs, methProp != null ? methProp.getKind() : SYMKIND.SK_MethodSymbol, mwi.GetType(), methProp, pObject, new CMemberLookupResults(GetGlobalSymbols().AllocParams(1, new CType[] { pType }), pName)); } public EXPRUSERDEFINEDCONVERSION CreateUserDefinedConversion(EXPR arg, EXPR call, MethWithInst mwi) { Debug.Assert(arg != null); Debug.Assert(call != null); EXPRUSERDEFINEDCONVERSION rval = new EXPRUSERDEFINEDCONVERSION(); rval.kind = ExpressionKind.EK_USERDEFINEDCONVERSION; rval.type = call.type; rval.flags = 0; rval.Argument = arg; rval.UserDefinedCall = call; rval.UserDefinedCallMethod = mwi; if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return rval; } public EXPRCAST CreateCast(EXPRFLAG nFlags, CType pType, EXPR pArg) { return CreateCast(nFlags, CreateClass(pType, null, null), pArg); } public EXPRCAST CreateCast(EXPRFLAG nFlags, EXPRTYPEORNAMESPACE pType, EXPR pArg) { Debug.Assert(pArg != null); Debug.Assert(pType != null); Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_CAST_ALL | EXPRFLAG.EXF_MASK_ANY))); EXPRCAST rval = new EXPRCAST(); rval.type = pType.TypeOrNamespace as CType; rval.kind = ExpressionKind.EK_CAST; rval.Argument = pArg; rval.flags = nFlags; rval.DestinationType = pType; Debug.Assert(rval != null); return (rval); } public EXPRRETURN CreateReturn(EXPRFLAG nFlags, Scope pCurrentScope, EXPR pOptionalObject) { return CreateReturn(nFlags, pCurrentScope, pOptionalObject, pOptionalObject); } public EXPRRETURN CreateReturn(EXPRFLAG nFlags, Scope pCurrentScope, EXPR pOptionalObject, EXPR pOptionalOriginalObject) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_ASLEAVE | EXPRFLAG.EXF_FINALLYBLOCKED | EXPRFLAG.EXF_RETURNISYIELD | EXPRFLAG.EXF_ASFINALLYLEAVE | EXPRFLAG.EXF_GENERATEDSTMT | EXPRFLAG.EXF_MARKING | EXPRFLAG.EXF_MASK_ANY ) )); EXPRRETURN rval = new EXPRRETURN(); rval.kind = ExpressionKind.EK_RETURN; rval.type = null; rval.flags = nFlags; rval.SetOptionalObject(pOptionalObject); Debug.Assert(rval != null); return (rval); } public EXPRLOCAL CreateLocal(EXPRFLAG nFlags, LocalVariableSymbol pLocal) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY))); CType type = null; if (pLocal != null) { type = pLocal.GetType(); } EXPRLOCAL rval = new EXPRLOCAL(); rval.kind = ExpressionKind.EK_LOCAL; rval.type = type; rval.flags = nFlags; rval.local = pLocal; Debug.Assert(rval != null); return (rval); } public EXPRTHISPOINTER CreateThis(LocalVariableSymbol pLocal, bool fImplicit) { Debug.Assert(pLocal == null || pLocal.isThis); CType type = null; if (pLocal != null) { type = pLocal.GetType(); } EXPRFLAG flags = EXPRFLAG.EXF_CANTBENULL; if (fImplicit) { flags |= EXPRFLAG.EXF_IMPLICITTHIS; } if (type != null && type.isStructType()) { flags |= EXPRFLAG.EXF_LVALUE; } EXPRTHISPOINTER rval = new EXPRTHISPOINTER(); rval.kind = ExpressionKind.EK_THISPOINTER; rval.type = type; rval.flags = flags; rval.local = pLocal; Debug.Assert(rval != null); return (rval); } public EXPRBOUNDLAMBDA CreateAnonymousMethod(AggregateType delegateType) { Debug.Assert(delegateType == null || delegateType.isDelegateType()); EXPRBOUNDLAMBDA rval = new EXPRBOUNDLAMBDA(); rval.kind = ExpressionKind.EK_BOUNDLAMBDA; rval.type = delegateType; rval.flags = 0; Debug.Assert(rval != null); return (rval); } public EXPRUNBOUNDLAMBDA CreateLambda() { CType type = GetTypes().GetAnonMethType(); EXPRUNBOUNDLAMBDA rval = new EXPRUNBOUNDLAMBDA(); rval.kind = ExpressionKind.EK_UNBOUNDLAMBDA; rval.type = type; rval.flags = 0; Debug.Assert(rval != null); return (rval); } public EXPRHOISTEDLOCALEXPR CreateHoistedLocalInExpression(EXPRLOCAL localToHoist) { Debug.Assert(localToHoist != null); EXPRHOISTEDLOCALEXPR rval = new EXPRHOISTEDLOCALEXPR(); rval.kind = ExpressionKind.EK_HOISTEDLOCALEXPR; rval.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_EXPRESSION).getThisType(); rval.flags = 0; return rval; } public EXPRMETHODINFO CreateMethodInfo(MethPropWithInst mwi) { return CreateMethodInfo(mwi.Meth(), mwi.GetType(), mwi.TypeArgs); } public EXPRMETHODINFO CreateMethodInfo(MethodSymbol method, AggregateType methodType, TypeArray methodParameters) { Debug.Assert(method != null); Debug.Assert(methodType != null); EXPRMETHODINFO methodInfo = new EXPRMETHODINFO(); CType type; if (method.IsConstructor()) { type = GetTypes().GetOptPredefAgg(PredefinedType.PT_CONSTRUCTORINFO).getThisType(); } else { type = GetTypes().GetOptPredefAgg(PredefinedType.PT_METHODINFO).getThisType(); } methodInfo.kind = ExpressionKind.EK_METHODINFO; methodInfo.type = type; methodInfo.flags = 0; methodInfo.Method = new MethWithInst(method, methodType, methodParameters); return methodInfo; } public EXPRPropertyInfo CreatePropertyInfo(PropertySymbol prop, AggregateType propertyType) { Debug.Assert(prop != null); Debug.Assert(propertyType != null); EXPRPropertyInfo propInfo = new EXPRPropertyInfo(); propInfo.kind = ExpressionKind.EK_PROPERTYINFO; propInfo.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_PROPERTYINFO).getThisType(); propInfo.flags = 0; propInfo.Property = new PropWithType(prop, propertyType); return propInfo; } public EXPRFIELDINFO CreateFieldInfo(FieldSymbol field, AggregateType fieldType) { Debug.Assert(field != null); Debug.Assert(fieldType != null); EXPRFIELDINFO rval = new EXPRFIELDINFO(); rval.kind = ExpressionKind.EK_FIELDINFO; rval.type = GetTypes().GetOptPredefAgg(PredefinedType.PT_FIELDINFO).getThisType(); ; rval.flags = 0; rval.Init(field, fieldType); return rval; } public EXPRTYPEOF CreateTypeOf(EXPRTYPEORNAMESPACE pSourceType) { EXPRTYPEOF rval = new EXPRTYPEOF(); rval.kind = ExpressionKind.EK_TYPEOF; rval.type = GetTypes().GetReqPredefAgg(PredefinedType.PT_TYPE).getThisType(); rval.flags = EXPRFLAG.EXF_CANTBENULL; rval.SetSourceType(pSourceType); Debug.Assert(rval != null); return (rval); } public EXPRTYPEOF CreateTypeOf(CType pSourceType) { return CreateTypeOf(MakeClass(pSourceType)); } public EXPRUSERLOGOP CreateUserLogOp(CType pType, EXPR pCallTF, EXPRCALL pCallOp) { Debug.Assert(pCallTF != null); Debug.Assert(pCallOp != null); Debug.Assert(pCallOp.GetOptionalArguments() != null); Debug.Assert(pCallOp.GetOptionalArguments().isLIST()); Debug.Assert(pCallOp.GetOptionalArguments().asLIST().GetOptionalElement() != null); EXPRUSERLOGOP rval = new EXPRUSERLOGOP(); EXPR leftChild = pCallOp.GetOptionalArguments().asLIST().GetOptionalElement(); Debug.Assert(leftChild != null); if (leftChild.isWRAP()) { // In the EE case, we don't create WRAPEXPRs. leftChild = leftChild.asWRAP().GetOptionalExpression(); Debug.Assert(leftChild != null); } rval.kind = ExpressionKind.EK_USERLOGOP; rval.type = pType; rval.flags = EXPRFLAG.EXF_ASSGOP; rval.TrueFalseCall = pCallTF; rval.OperatorCall = pCallOp; rval.FirstOperandToExamine = leftChild; Debug.Assert(rval != null); return (rval); } public EXPRUSERLOGOP CreateUserLogOpError(CType pType, EXPR pCallTF, EXPRCALL pCallOp) { EXPRUSERLOGOP rval = CreateUserLogOp(pType, pCallTF, pCallOp); rval.SetError(); return rval; } public EXPRCONCAT CreateConcat(EXPR op1, EXPR op2) { Debug.Assert(op1 != null && op1.type != null); Debug.Assert(op2 != null && op2.type != null); Debug.Assert(op1.type.isPredefType(PredefinedType.PT_STRING) || op2.type.isPredefType(PredefinedType.PT_STRING)); CType type = op1.type; if (!type.isPredefType(PredefinedType.PT_STRING)) { type = op2.type; } Debug.Assert(type.isPredefType(PredefinedType.PT_STRING)); EXPRCONCAT rval = new EXPRCONCAT(); rval.kind = ExpressionKind.EK_CONCAT; rval.type = type; rval.flags = 0; rval.SetFirstArgument(op1); rval.SetSecondArgument(op2); Debug.Assert(rval != null); return (rval); } public EXPRCONSTANT CreateStringConstant(string str) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_STRING).getThisType(), _constants.Create(str)); } public EXPRMULTIGET CreateMultiGet(EXPRFLAG nFlags, CType pType, EXPRMULTI pOptionalMulti) { Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY))); EXPRMULTIGET rval = new EXPRMULTIGET(); rval.kind = ExpressionKind.EK_MULTIGET; rval.type = pType; rval.flags = nFlags; rval.SetOptionalMulti(pOptionalMulti); Debug.Assert(rval != null); return (rval); } public EXPRMULTI CreateMulti(EXPRFLAG nFlags, CType pType, EXPR pLeft, EXPR pOp) { Debug.Assert(pLeft != null); Debug.Assert(pOp != null); EXPRMULTI rval = new EXPRMULTI(); rval.kind = ExpressionKind.EK_MULTI; rval.type = pType; rval.flags = nFlags; rval.SetLeft(pLeft); rval.SetOperator(pOp); Debug.Assert(rval != null); return (rval); } //////////////////////////////////////////////////////////////////////////////// // // Precondition: // // pType - Non-null // // This returns a null for reference types and an EXPRZEROINIT for all others. public EXPR CreateZeroInit(CType pType) { EXPRCLASS exprClass = MakeClass(pType); return CreateZeroInit(exprClass); } public EXPR CreateZeroInit(EXPRTYPEORNAMESPACE pTypeExpr) { return CreateZeroInit(pTypeExpr, null, false); } private EXPR CreateZeroInit(EXPRTYPEORNAMESPACE pTypeExpr, EXPR pOptionalOriginalConstructorCall, bool isConstructor) { Debug.Assert(pTypeExpr != null); CType pType = pTypeExpr.TypeOrNamespace.AsType(); bool bIsError = false; if (pType.isEnumType()) { // For enum types, we create a constant that has the default value // as an object pointer. ConstValFactory factory = new ConstValFactory(); EXPRCONSTANT expr = CreateConstant(pType, factory.Create(Activator.CreateInstance(pType.AssociatedSystemType))); return expr; } switch (pType.fundType()) { default: bIsError = true; break; case FUNDTYPE.FT_PTR: { CType nullType = GetTypes().GetNullType(); // It looks like this if is always false ... if (nullType.fundType() == pType.fundType()) { // Create a constant here. EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(ConstValKind.IntPtr)); return (expr); } // Just allocate a new node and fill it in. EXPRCAST cast = CreateCast(0, pTypeExpr, CreateNull()); return (cast); } case FUNDTYPE.FT_REF: case FUNDTYPE.FT_I1: case FUNDTYPE.FT_U1: case FUNDTYPE.FT_I2: case FUNDTYPE.FT_U2: case FUNDTYPE.FT_I4: case FUNDTYPE.FT_U4: case FUNDTYPE.FT_I8: case FUNDTYPE.FT_U8: case FUNDTYPE.FT_R4: case FUNDTYPE.FT_R8: { EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); EXPRCONSTANT exprInOriginal = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); exprInOriginal.SetOptionalConstructorCall(pOptionalOriginalConstructorCall); return expr; } case FUNDTYPE.FT_STRUCT: if (pType.isPredefType(PredefinedType.PT_DECIMAL)) { EXPRCONSTANT expr = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); EXPRCONSTANT exprOriginal = CreateConstant(pType, ConstValFactory.GetDefaultValue(pType.constValKind())); exprOriginal.SetOptionalConstructorCall(pOptionalOriginalConstructorCall); return expr; } break; case FUNDTYPE.FT_VAR: break; } EXPRZEROINIT rval = new EXPRZEROINIT(); rval.kind = ExpressionKind.EK_ZEROINIT; rval.type = pType; rval.flags = 0; rval.OptionalConstructorCall = pOptionalOriginalConstructorCall; rval.IsConstructor = isConstructor; if (bIsError) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRCONSTANT CreateConstant(CType pType, CONSTVAL constVal) { return CreateConstant(pType, constVal, null); } public EXPRCONSTANT CreateConstant(CType pType, CONSTVAL constVal, EXPR pOriginal) { EXPRCONSTANT rval = CreateConstant(pType); rval.setVal(constVal); Debug.Assert(rval != null); return (rval); } public EXPRCONSTANT CreateConstant(CType pType) { EXPRCONSTANT rval = new EXPRCONSTANT(); rval.kind = ExpressionKind.EK_CONSTANT; rval.type = pType; rval.flags = 0; return rval; } public EXPRCONSTANT CreateIntegerConstant(int x) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(), ConstValFactory.GetInt(x)); } public EXPRCONSTANT CreateBoolConstant(bool b) { return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_BOOL).getThisType(), ConstValFactory.GetBool(b)); } public EXPRBLOCK CreateBlock(EXPRBLOCK pOptionalCurrentBlock, EXPRSTMT pOptionalStatements, Scope pOptionalScope) { EXPRBLOCK rval = new EXPRBLOCK(); rval.kind = ExpressionKind.EK_BLOCK; rval.type = null; rval.flags = 0; rval.SetOptionalStatements(pOptionalStatements); rval.OptionalScopeSymbol = pOptionalScope; Debug.Assert(rval != null); return (rval); } public EXPRQUESTIONMARK CreateQuestionMark(EXPR pTestExpression, EXPRBINOP pConsequence) { Debug.Assert(pTestExpression != null); Debug.Assert(pConsequence != null); CType pType = pConsequence.type; if (pType == null) { Debug.Assert(pConsequence.GetOptionalLeftChild() != null); pType = pConsequence.GetOptionalLeftChild().type; Debug.Assert(pType != null); } EXPRQUESTIONMARK pResult = new EXPRQUESTIONMARK(); pResult.kind = ExpressionKind.EK_QUESTIONMARK; pResult.type = pType; pResult.flags = 0; pResult.SetTestExpression(pTestExpression); pResult.SetConsequence(pConsequence); Debug.Assert(pResult != null); return pResult; } public EXPRARRAYINDEX CreateArrayIndex(EXPR pArray, EXPR pIndex) { CType pType = pArray.type; if (pType != null && pType.IsArrayType()) { pType = pType.AsArrayType().GetElementType(); } else if (pType == null) { pType = GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(); } EXPRARRAYINDEX pResult = new EXPRARRAYINDEX(); pResult.kind = ExpressionKind.EK_ARRAYINDEX; pResult.type = pType; pResult.flags = 0; pResult.SetArray(pArray); pResult.SetIndex(pIndex); return pResult; } public EXPRARRAYLENGTH CreateArrayLength(EXPR pArray) { EXPRARRAYLENGTH pResult = new EXPRARRAYLENGTH(); pResult.kind = ExpressionKind.EK_ARRAYLENGTH; pResult.type = GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(); pResult.flags = 0; pResult.SetArray(pArray); return pResult; } public EXPRBINOP CreateBinop(ExpressionKind exprKind, CType pType, EXPR p1, EXPR p2) { //Debug.Assert(exprKind.isBinaryOperator()); EXPRBINOP rval = new EXPRBINOP(); rval.kind = exprKind; rval.type = pType; rval.flags = EXPRFLAG.EXF_BINOP; rval.SetOptionalLeftChild(p1); rval.SetOptionalRightChild(p2); rval.isLifted = false; rval.SetOptionalUserDefinedCall(null); rval.SetUserDefinedCallMethod(null); Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateUnaryOp(ExpressionKind exprKind, CType pType, EXPR pOperand) { Debug.Assert(exprKind.isUnaryOperator()); Debug.Assert(pOperand != null); EXPRUNARYOP rval = new EXPRUNARYOP(); rval.kind = exprKind; rval.type = pType; rval.flags = 0; rval.Child = pOperand; rval.OptionalUserDefinedCall = null; rval.UserDefinedCallMethod = null; Debug.Assert(rval != null); return (rval); } public EXPR CreateOperator(ExpressionKind exprKind, CType pType, EXPR pArg1, EXPR pOptionalArg2) { Debug.Assert(pArg1 != null); EXPR rval = null; if (exprKind.isUnaryOperator()) { Debug.Assert(pOptionalArg2 == null); rval = CreateUnaryOp(exprKind, pType, pArg1); } else rval = CreateBinop(exprKind, pType, pArg1, pOptionalArg2); Debug.Assert(rval != null); return rval; } public EXPRBINOP CreateUserDefinedBinop(ExpressionKind exprKind, CType pType, EXPR p1, EXPR p2, EXPR call, MethPropWithInst pmpwi) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); Debug.Assert(call != null); EXPRBINOP rval = new EXPRBINOP(); rval.kind = exprKind; rval.type = pType; rval.flags = EXPRFLAG.EXF_BINOP; rval.SetOptionalLeftChild(p1); rval.SetOptionalRightChild(p2); // The call may be lifted, but we do not mark the outer binop as lifted. rval.isLifted = false; rval.SetOptionalUserDefinedCall(call); rval.SetUserDefinedCallMethod(pmpwi); if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateUserDefinedUnaryOperator(ExpressionKind exprKind, CType pType, EXPR pOperand, EXPR call, MethPropWithInst pmpwi) { Debug.Assert(pType != null); Debug.Assert(pOperand != null); Debug.Assert(call != null); Debug.Assert(pmpwi != null); EXPRUNARYOP rval = new EXPRUNARYOP(); rval.kind = exprKind; rval.type = pType; rval.flags = 0; rval.Child = pOperand; // The call may be lifted, but we do not mark the outer binop as lifted. rval.OptionalUserDefinedCall = call; rval.UserDefinedCallMethod = pmpwi; if (call.HasError()) { rval.SetError(); } Debug.Assert(rval != null); return (rval); } public EXPRUNARYOP CreateNeg(EXPRFLAG nFlags, EXPR pOperand) { Debug.Assert(pOperand != null); EXPRUNARYOP pUnaryOp = CreateUnaryOp(ExpressionKind.EK_NEG, pOperand.type, pOperand); pUnaryOp.flags |= nFlags; return pUnaryOp; } //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the second. public EXPRBINOP CreateSequence(EXPR p1, EXPR p2) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); return CreateBinop(ExpressionKind.EK_SEQUENCE, p2.type, p1, p2); } //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the first. public EXPRBINOP CreateReverseSequence(EXPR p1, EXPR p2) { Debug.Assert(p1 != null); Debug.Assert(p2 != null); return CreateBinop(ExpressionKind.EK_SEQREV, p1.type, p1, p2); } public EXPRASSIGNMENT CreateAssignment(EXPR pLHS, EXPR pRHS) { EXPRASSIGNMENT pAssignment = new EXPRASSIGNMENT(); pAssignment.kind = ExpressionKind.EK_ASSIGNMENT; pAssignment.type = pLHS.type; pAssignment.flags = EXPRFLAG.EXF_ASSGOP; pAssignment.SetLHS(pLHS); pAssignment.SetRHS(pRHS); return pAssignment; } //////////////////////////////////////////////////////////////////////////////// public EXPRNamedArgumentSpecification CreateNamedArgumentSpecification(Name pName, EXPR pValue) { EXPRNamedArgumentSpecification pResult = new EXPRNamedArgumentSpecification(); pResult.kind = ExpressionKind.EK_NamedArgumentSpecification; pResult.type = pValue.type; pResult.flags = 0; pResult.Value = pValue; pResult.Name = pName; return pResult; } public EXPRWRAP CreateWrap( Scope pCurrentScope, EXPR pOptionalExpression ) { EXPRWRAP rval = new EXPRWRAP(); rval.kind = ExpressionKind.EK_WRAP; rval.type = null; rval.flags = 0; rval.SetOptionalExpression(pOptionalExpression); if (pOptionalExpression != null) { rval.setType(pOptionalExpression.type); } rval.flags |= EXPRFLAG.EXF_LVALUE; Debug.Assert(rval != null); return (rval); } public EXPRWRAP CreateWrapNoAutoFree(Scope pCurrentScope, EXPR pOptionalWrap) { EXPRWRAP rval = CreateWrap(pCurrentScope, pOptionalWrap); return rval; } public EXPRBINOP CreateSave(EXPRWRAP wrap) { Debug.Assert(wrap != null); EXPRBINOP expr = CreateBinop(ExpressionKind.EK_SAVE, wrap.type, wrap.GetOptionalExpression(), wrap); expr.setAssignment(); return expr; } public EXPR CreateNull() { return CreateConstant(GetTypes().GetNullType(), ConstValFactory.GetNullRef()); } public void AppendItemToList( EXPR newItem, ref EXPR first, ref EXPR last ) { if (newItem == null) { // Nothing changes. return; } if (first == null) { Debug.Assert(last == first); first = newItem; last = newItem; return; } if (first.kind != ExpressionKind.EK_LIST) { Debug.Assert(last == first); first = CreateList(first, newItem); last = first; return; } Debug.Assert(last.kind == ExpressionKind.EK_LIST); Debug.Assert(last.asLIST().OptionalNextListNode != null); Debug.Assert(last.asLIST().OptionalNextListNode.kind != ExpressionKind.EK_LIST); last.asLIST().OptionalNextListNode = CreateList(last.asLIST().OptionalNextListNode, newItem); last = last.asLIST().OptionalNextListNode; } public EXPRLIST CreateList(EXPR op1, EXPR op2) { EXPRLIST rval = new EXPRLIST(); rval.kind = ExpressionKind.EK_LIST; rval.type = null; rval.flags = 0; rval.SetOptionalElement(op1); rval.SetOptionalNextListNode(op2); Debug.Assert(rval != null); return (rval); } public EXPRLIST CreateList(EXPR op1, EXPR op2, EXPR op3) { return CreateList(op1, CreateList(op2, op3)); } public EXPRLIST CreateList(EXPR op1, EXPR op2, EXPR op3, EXPR op4) { return CreateList(op1, CreateList(op2, CreateList(op3, op4))); } public EXPRTYPEARGUMENTS CreateTypeArguments(TypeArray pTypeArray, EXPR pOptionalElements) { Debug.Assert(pTypeArray != null); EXPRTYPEARGUMENTS rval = new EXPRTYPEARGUMENTS(); rval.kind = ExpressionKind.EK_TYPEARGUMENTS; rval.type = null; rval.flags = 0; rval.SetOptionalElements(pOptionalElements); return rval; } public EXPRCLASS CreateClass(CType pType, EXPR pOptionalLHS, EXPRTYPEARGUMENTS pOptionalTypeArguments) { Debug.Assert(pType != null); EXPRCLASS rval = new EXPRCLASS(); rval.kind = ExpressionKind.EK_CLASS; rval.type = pType; rval.TypeOrNamespace = pType; Debug.Assert(rval != null); return (rval); } public EXPRCLASS MakeClass(CType pType) { Debug.Assert(pType != null); return CreateClass(pType, null/* LHS */, null/* type arguments */); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> internal sealed partial class UnixFileStream : FileStreamBase { /// <summary>The file descriptor wrapped in a file handle.</summary> private readonly SafeFileHandle _fileHandle; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>File mode.</summary> private readonly FileMode _mode; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>Advanced options requested when opening the file.</summary> private readonly FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private readonly long _appendStart = -1; /// <summary>Whether asynchronous read/write/flush operations should be performed using async I/O.</summary> private readonly bool _useAsyncIO; /// <summary>The length of the _buffer.</summary> private readonly int _bufferLength; /// <summary>Lazily-initialized buffer data from Write waiting to be written to the underlying handle, or data read from the underlying handle and waiting to be Read.</summary> private byte[] _buffer; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file descriptor's actual position, /// and should only ever be out of sync if another stream with access to this same file descriptor manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="path">The path to the file.</param> /// <param name="mode">How the file should be opened.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="options">Additional options for working with the file.</param> internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) : base(parent) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _path = path; _access = access; _mode = mode; _options = options; _bufferLength = bufferSize; _useAsyncIO = (options & FileOptions.Asynchronous) != 0; // Translate the arguments into arguments for an open call Interop.libc.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored Interop.libc.Permissions openPermissions = Interop.libc.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized. _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions); _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. try { Interop.libc.LockOperations lockOperation = (share == FileShare.None) ? Interop.libc.LockOperations.LOCK_EX : Interop.libc.LockOperations.LOCK_SH; SysCall<Interop.libc.LockOperations, int>((fd, op, _) => Interop.libc.flock(fd, op), lockOperation | Interop.libc.LockOperations.LOCK_NB); } catch { _fileHandle.Dispose(); throw; } // Perform additional configurations on the stream based on the provided FileOptions PostOpenConfigureStreamFromOptions(); // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(0, SeekOrigin.End); } } /// <summary>Performs additional configuration of the opened stream based on provided options.</summary> partial void PostOpenConfigureStreamFromOptions(); /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> /// <param name="handle">The handle to the file.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param> internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent) : base(parent) { // Make sure the handle is open if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, "handle"); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum); if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync); _fileHandle = handle; _access = access; _exposedHandle = true; _bufferLength = bufferSize; _useAsyncIO = useAsyncIO; if (CanSeek) { SeekCore(0, SeekOrigin.Current); } } /// <summary>Gets the array used for buffering reading and writing. If the array hasn't been allocated, this will lazily allocate it.</summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); return _buffer ?? (_buffer = new byte[_bufferLength]); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.libc.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.libc.OpenFlags flags = default(Interop.libc.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.libc.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.libc.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.libc.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.libc.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.libc.OpenFlags.O_WRONLY; break; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. switch (options) { case FileOptions.Asynchronous: // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true case FileOptions.DeleteOnClose: // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose case FileOptions.Encrypted: // Encrypted does not have an equivalent on Unix and is ignored. case FileOptions.RandomAccess: // Implemented after open if posix_fadvise is available case FileOptions.SequentialScan: // Implemented after open if posix_fadvise is available break; case FileOptions.WriteThrough: flags |= Interop.libc.OpenFlags.O_SYNC; break; } return flags; } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek { get { if (_fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = SysCall<int, int>((fd, _, __) => Interop.libc.lseek(fd, 0, Interop.libc.SeekWhence.SEEK_CUR), throwOnError: false) >= 0; } return _canSeek.Value; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public override bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } // Get the length of the file as reported by the OS long length = SysCall<int, int>((fd, _, __) => { Interop.libcoreclr.fileinfo fileinfo; int result = Interop.libcoreclr.GetFileInformationFromFd(fd, out fileinfo); return result >= 0 ? fileinfo.size : result; }); // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } } /// <summary>Gets the path that was passed to the constructor.</summary> public override String Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets the SafeFileHandle for the file descriptor encapsulated in this stream.</summary> public override SafeFileHandle SafeFileHandle { get { _parent.Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } _parent.Seek(value, SeekOrigin.Begin); } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void VerifyBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && _parent.CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { // Flush and close the file try { if (_fileHandle != null && !_fileHandle.IsClosed) { FlushWriteBuffer(); // Unix doesn't directly support DeleteOnClose but we can mimick it. if ((_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed. Interop.libc.unlink(_path); // ignore any error } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Finalize the stream.</summary> ~UnixFileStream() { Dispose(false); } /// <summary>Clears buffers for this stream and causes any buffered data to be written to the file.</summary> public override void Flush() { _parent.Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public override void Flush(Boolean flushToDisk) { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } FlushInternalBuffer(); if (flushToDisk && _parent.CanWrite) { FlushOSBuffer(); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { SysCall<int, int>((fd, _, __) => Interop.libc.fsync(fd)); } /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && _parent.CanSeek) { FlushReadBuffer(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { WriteCore(GetBuffer(), 0, _writePos); _writePos = 0; } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { VerifyBufferInvariants(); int rewind = _readPos - _readLength; if (rewind != 0) { SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (_parent.CanWrite) { return Task.Factory.StartNew( state => ((UnixFileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } if (!_parent.CanWrite) { throw __Error.GetWriteNotSupported(); } FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(value, SeekOrigin.Begin); } SysCall<long, int>((fd, length, _) => Interop.libc.ftruncate(fd, length), value); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(origPos, SeekOrigin.Begin); } else { SeekCore(0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> public override int Read([In, Out] byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!_parent.CanSeek || (count >= _bufferLength)) { // Read directly into the user's buffer int bytesRead = ReadCore(array, offset, count); _readPos = _readLength = 0; // reset after the read just in case read experiences an exception return bytesRead; } else { // Read into our buffer. _readLength = numBytesAvailable = ReadCore(GetBuffer(), 0, _bufferLength); _readPos = 0; if (numBytesAvailable == 0) { return 0; } } } // Now that we know there's data in the buffer, read from it into // the user's buffer. int bytesToRead = Math.Min(numBytesAvailable, count); Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesToRead); _readPos += bytesToRead; return bytesToRead; } /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadCore(byte[] array, int offset, int count) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = array) { bytesRead = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.ReadAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Reads a byte from the stream and advances the position within the stream /// by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { _readLength = ReadCore(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (_readLength == 0 && !_parent.CanRead) { throw __Error.GetReadNotSupported(); } VerifyBufferInvariants(); } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForWriting(); // If no data is being written, nothing more to do. if (count == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining > 0) { int bytesToCopy = Math.Min(spaceRemaining, count); Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy); _writePos += bytesToCopy; // If we've successfully copied all of the user's data, we're done. if (count == bytesToCopy) { return; } // Otherwise, keep track of how much more data needs to be handled. offset += bytesToCopy; count -= bytesToCopy; } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (count >= _bufferLength) { WriteCore(array, offset, count); } else { Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count); _writePos = count; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private unsafe void WriteCore(byte[] array, int offset, int count) { VerifyOSHandlePosition(); fixed (byte* bufPtr = array) { while (count > 0) { int bytesWritten = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); _filePosition += bytesWritten; count -= bytesWritten; offset += bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.WriteAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) // avoids an array allocation in the base implementation { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) { FlushWriteBuffer(); } // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!_parent.CanWrite) throw __Error.GetWriteNotSupported(); FlushReadBuffer(); } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, "origin"); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(long offset, SeekOrigin origin) { Debug.Assert(!_fileHandle.IsClosed && CanSeek); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = SysCall((fd, off, or) => Interop.libc.lseek(fd, off, or), offset, (Interop.libc.SeekWhence)(int)origin); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <typeparam name="TArg1">Specifies the type of an argument to the system call.</typeparam> /// <typeparam name="TArg2">Specifies the type of another argument to the system call.</typeparam> /// <param name="sysCall">A delegate that invokes the system call.</param> /// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param> /// <param name="arg2">The second argument to be passed to the system call.</param> /// <param name="throwOnError">true to throw an exception if a non-interuption error occurs; otherwise, false.</param> /// <returns>The return value of the system call.</returns> /// <remarks> /// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/> /// so as to avoid delegate and closure allocations at the call sites. /// </remarks> private long SysCall<TArg1, TArg2>( Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1 = default(TArg1), TArg2 arg2 = default(TArg2), bool throwOnError = true) { SafeFileHandle handle = _fileHandle; Debug.Assert(sysCall != null); Debug.Assert(handle != null); bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. handle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)handle.DangerousGetHandle(); Debug.Assert(fd >= 0); // System calls may fail due to EINTR (signal interruption). We need to retry in those cases. while (true) { long result = sysCall(fd, arg1, arg2); if (result < 0) { int errno = Marshal.GetLastWin32Error(); if (errno == Interop.Errors.EINTR) { continue; } else if (throwOnError) { throw Interop.GetExceptionForIoErrno(errno, _path, isDirectory: false); } } return result; } } finally { if (gotRefOnHandle) { handle.DangerousRelease(); } else { throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); } } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using RubiksCube.HUD; namespace RubiksCube { /// <summary> /// This is the main type for your game /// </summary> public class CubeGame : Microsoft.Xna.Framework.Game { private Panel _Panel; private Vector3 Debug_MouseP1; private Vector3 Debug_MouseP2; private bool IsMouseDragging = true; private Ray MouseRay; private readonly GraphicsDeviceManager Graphics; private GraphicsDevice Device; private SpriteBatch spriteBatch; private SpriteFont Font; private BasicEffect Effect; private BasicCamera Camera; private ArcBall ArcBall; private Cube TheCube; public CubeGame() { Graphics = new GraphicsDeviceManager(this); Graphics.PreferredBackBufferWidth = 1024; Graphics.PreferredBackBufferHeight = 768; Graphics.PreferMultiSampling = true; Content.RootDirectory = "Content"; TheCube = new Cube(); } private bool CheckKeyPress(KeyboardState kb, Keys key) { return !KeysWerePressed.Contains(key) && kb.IsKeyDown(key); } private Keys[] KeysWerePressed = new Keys[0]; /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here Device = Graphics.GraphicsDevice; Device.PresentationParameters.MultiSampleCount = 8; //Device.PresentationParameters.IsFullScreen = true; Graphics.ApplyChanges(); Device.Reset(Device.PresentationParameters); Effect = new BasicEffect(Device) { VertexColorEnabled = true }; //Effect.EnableDefaultLighting(); IsMouseVisible = true; Camera = new BasicCamera(new Vector3(0, 0, 10), Vector3.Zero, Device.Viewport.AspectRatio); //ArcBall = new ArcBall(Device, Camera) { Rotation = Matrix.CreateRotationY(-MathHelper.PiOver4) }; ArcBall = new ArcBall(Device, Camera) { Rotation = Matrix.CreateRotationY(-MathHelper.PiOver4) * Matrix.CreateRotationX(MathHelper.PiOver4 / 3 * 2)}; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); Font = Content.Load<SpriteFont>("Fonts/DefaultUI"); var texture = Content.Load<Texture2D>("Textures/PlainCubie"); Effect.Texture = texture; Effect.TextureEnabled = true; Effect.View = Camera.ViewMatrix; Effect.Projection = Camera.ProjectionMatrix; UpdateWorldTransform(); _Panel = new Panel(Device, Device.Viewport.Width, 44); _Panel.Controls.Add(new Button(Device, "Scramble", Font, Color.Black)); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState kb = Keyboard.GetState(); if (kb.IsKeyDown(Keys.Escape)) this.Exit(); base.Update(gameTime); bool shift = kb.IsKeyDown(Keys.LeftShift) || kb.IsKeyDown(Keys.RightShift); if (CheckKeyPress(kb, Keys.F)) TheCube.Move(Cube.FRONT, !shift); if (CheckKeyPress(kb, Keys.B)) TheCube.Move(Cube.BACK, !shift); if (CheckKeyPress(kb, Keys.L)) TheCube.Move(Cube.LEFT, !shift); if (CheckKeyPress(kb, Keys.R)) TheCube.Move(Cube.RIGHT, !shift); if (CheckKeyPress(kb, Keys.U)) TheCube.Move(Cube.UP, !shift); if (CheckKeyPress(kb, Keys.D)) TheCube.Move(Cube.DOWN, !shift); if (kb.GetPressedKeys().Length > 4) { TheCube.FuckThis(); } KeysWerePressed = kb.GetPressedKeys(); DoMouseGestures(); var mouse = Mouse.GetState(); if (mouse.LeftButton == ButtonState.Pressed) { if (!buttonClickProcessed) { var ctrl = _Panel.GetControlAt(mouse.X, mouse.Y - Device.Viewport.Height + _Panel.Height); if (ctrl != null) { var rand = new Random(); for (int i = 0; i < 20; i++) { int x = rand.Next(6); TheCube.Move(x, true, 0.07f); } } buttonClickProcessed = true; } } else { buttonClickProcessed = false; } TheCube.Update(gameTime); DoMouseLook(); } private bool buttonClickProcessed = false; private void DoMouseGestures() { var mouse = Mouse.GetState(); if (mouse.LeftButton == ButtonState.Pressed) { Vector3 nearsource = new Vector3((float)mouse.X, (float)mouse.Y, 0f); Vector3 farsource = new Vector3((float)mouse.X, (float)mouse.Y, 1f); Matrix world = Effect.World; var NearPoint = GraphicsDevice.Viewport.Unproject(nearsource, Camera.ProjectionMatrix, Camera.ViewMatrix, world); var FarPoint = GraphicsDevice.Viewport.Unproject(farsource, Camera.ProjectionMatrix, Camera.ViewMatrix, world); // Create a ray from the near clip plane to the far clip plane. Vector3 direction = FarPoint - NearPoint; direction.Normalize(); MouseRay = new Ray(NearPoint, direction); if (IsMouseDragging) { TheCube.UpdateMouseGesture(MouseRay); Debug_MouseP2 = TheCube.MouseMoveEndPoint; //IsMouseDragging = !TheCube.EndMouseGesture(); } else { //TheCube.Debug_HighlightIntersectedCubies(MouseRay); if (TheCube.BeginMouseGesture(MouseRay)) { Debug_MouseP1 = TheCube.MouseMoveStartPoint; IsMouseDragging = true; } } } else { if (IsMouseDragging) { TheCube.EndMouseGesture(); IsMouseDragging = false; } } } private void DoMouseLook() { var mouse = Mouse.GetState(); if (mouse.RightButton == ButtonState.Pressed) { if (!ArcBall.IsDragging) { ArcBall.StartDrag(mouse); } else if (ArcBall.IsDragging) { ArcBall.UpdateDrag(mouse); UpdateWorldTransform(); } } else { if (ArcBall.IsDragging) { ArcBall.EndDrag(); } } } private void UpdateWorldTransform() { Effect.World = ArcBall.Rotation; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); GraphicsDevice.SamplerStates[0] = SamplerState.AnisotropicClamp; GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; // TODO: Add your drawing code here foreach (var pass in Effect.CurrentTechnique.Passes) { Effect.TextureEnabled = true; pass.Apply(); // commented stuff is an attempt to render mirrored cube // it works, but it screws up the ArcBall and mouse gestures. //var save = Effect.World; //Effect.World = save * Matrix.CreateRotationY(MathHelper.Pi) * Matrix.CreateTranslation(-2.5f, 0, 0); //pass.Apply(); //TheCube.Draw(Effect); //Effect.World = save * Matrix.CreateTranslation(2.5f, 0, 0); //pass.Apply(); TheCube.Draw(Effect); //Effect.World = save; Effect.TextureEnabled = false; pass.Apply(); GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, new[] { new VertexPositionColor(Debug_MouseP2, Color.Violet), new VertexPositionColor(Debug_MouseP1 , Color.Black), }, 0, 1 ); } spriteBatch.Begin(); _Panel.Paint(spriteBatch, new Vector2(0, Device.Viewport.Height - _Panel.Height)); spriteBatch.End(); base.Draw(gameTime); } } }
//options settings //Screen and Display menu //Renderer Mode //Screen resolution //Windowed/fullscreen(borderless?) //VSync //Screen brightness //screen brightness //screen gamma //Lighting Menu //Shadow Distance(Distance shadows are drawn to. Also affects shadowmap slices) //Shadow Quality(Resolution of shadows rendered, setting to none disables dynamic shadows) //Soft Shadows(Whether shadow softening is used) //Shadow caching(If the lights enable it, shadow caching is activated) //Light Draw Distance(How far away lights are still drawn. Doesn't impact vector lights like the sun) //Mesh and Textures Menu //Draw distance(Overall draw distance) -slider //Object draw distance(Draw distance from small/unimportant objects) -slider //Mesh quality //Texture quality //Foliage draw distance //Terrain Quality //Decal Quality //Effects Menu //Parallax //HDR //Light shafts //Motion Blur //Depth of Field //SSAO //AA(ModelXAmount)[defualt is FXAA] //Anisotropic filtering //Keybinds //Camera //horizontal mouse sensitivity //vert mouse sensitivity //invert vertical //zoom mouse sensitivities(both horz/vert) //headbob //FOV function OptionsMenu::onWake(%this) { OptionsMain.hidden = false; ControlsMenu.hidden = true; GraphicsMenu.hidden = true; AudioMenu.hidden = true; CameraMenu.hidden = true; ScreenBrightnessMenu.hidden = true; OptionsOKButton.hidden = false; OptionsCancelButton.hidden = false; OptionsDefaultsButton.hidden = false; } function OptionsMenuOKButton::onClick(%this) { //save the settings and then back out OptionsMenu.backOut(); } function OptionsMenuCancelButton::onClick(%this) { //we don't save, so go straight to backing out of the menu OptionsMenu.backOut(); } function OptionsMenuDefaultsButton::onClick(%this) { //we don't save, so go straight to backing out of the menu OptionsMenu.backOut(); } function ControlsSettingsMenuButton::onClick(%this) { OptionsMain.hidden = true; ControlsMenu.hidden = false; KeyboardControlPanel.hidden = false; MouseControlPanel.hidden = true; ControlsMenu.reload(); } function GraphicsSettingsMenuButton::onClick(%this) { OptionsMain.hidden = true; GraphicsMenu.hidden = false; } function CameraSettingsMenuButton::onClick(%this) { OptionsMain.hidden = true; CameraMenu.hidden = false; CameraMenu.loadSettings(); } function AudioSettingsMenuButton::onClick(%this) { OptionsMain.hidden = true; AudioMenu.hidden = false; AudioMenu.loadSettings(); } function ScreenBrSettingsMenuButton::onClick(%this) { OptionsMain.hidden = true; ScreenBrightnessMenu.hidden = false; } function OptionsMenu::backOut(%this) { //save the settings and then back out if(OptionsMain.hidden == false) { //we're not in a specific menu, so we're actually exiting Canvas.popDialog(OptionsMenu); if(isObject(OptionsMenu.returnGui) && OptionsMenu.returnGui.isMethod("onReturnTo")) OptionsMenu.returnGui.onReturnTo(); } else { OptionsMain.hidden = false; ControlsMenu.hidden = true; GraphicsMenu.hidden = true; CameraMenu.hidden = true; AudioMenu.hidden = true; ScreenBrightnessMenu.hidden = true; } } function OptionsMenu::addSettingOption(%this, %arrayTarget) { %graphicsOption = OptionsMenu.tamlReader.read("data/ui/scripts/guis/graphicsMenuSettingsCtrl.taml"); %arrayTarget.add(%graphicsOption); return %graphicsOption; } function OptionsMenu::addSliderOption(%this, %arrayTarget, %range, %ticks, %variable, %value, %class) { %graphicsOption = OptionsMenu.tamlReader.read("data/ui/scripts/guis/graphicsMenuSettingsSlider.taml"); %arrayTarget.add(%graphicsOption); if(%range !$= "") { %graphicsOption-->slider.range = %range; } if(%ticks !$= "") { %graphicsOption-->slider.ticks = %ticks; } if(%variable !$= "") { %graphicsOption-->slider.variable = %variable; } if(%value !$= "") { %graphicsOption-->slider.setValue(%value); } if(%class !$= "") { %graphicsOption-->slider.className = %class; } else %graphicsOption-->slider.className = OptionsMenuSlider; %graphicsOption-->slider.snap = true; %graphicsOption-->slider.onValueSet(); return %graphicsOption; } function OptionsMenuSlider::onMouseDragged(%this) { %this.onValueSet(); } function OptionsMenuSlider::onValueSet(%this) { %this.getParent().getParent()-->valueText.setText(mRound(%this.value * 10)); } function FOVOptionSlider::onMouseDragged(%this) { %this.onValueSet(); } function FOVOptionSlider::onValueSet(%this) { %this.getParent().getParent()-->valueText.setText(mRound(%this.value)); } /// Returns true if the current quality settings equal /// this graphics quality level. function OptionsMenuSettingLevel::isCurrent( %this ) { // Test each pref to see if the current value // equals our stored value. for ( %i=0; %i < %this.count(); %i++ ) { %pref = %this.getKey( %i ); %value = %this.getValue( %i ); %prefVarValue = getVariable( %pref ); if ( getVariable( %pref ) !$= %value ) return false; } return true; } // ============================================================================= // CAMERA MENU // ============================================================================= function CameraMenu::onWake(%this) { } function CameraMenu::apply(%this) { setFOV($pref::Player::defaultFov); } function CameraMenu::loadSettings(%this) { CameraMenuOptionsArray.clear(); %option = OptionsMenu.addSettingOption(CameraMenuOptionsArray); %option-->nameText.setText("Invert Vertical"); %option.qualitySettingGroup = InvertVerticalMouse; %option.init(); %option = OptionsMenu.addSliderOption(CameraMenuOptionsArray, "0.1 1", 8, "$pref::Input::VertMouseSensitivity", $pref::Input::VertMouseSensitivity); %option-->nameText.setText("Vertical Sensitivity"); %option = OptionsMenu.addSliderOption(CameraMenuOptionsArray, "0.1 1", 8, "$pref::Input::HorzMouseSensitivity", $pref::Input::HorzMouseSensitivity); %option-->nameText.setText("Horizontal Sensitivity"); %option = OptionsMenu.addSliderOption(CameraMenuOptionsArray, "0.1 1", 8, "$pref::Input::ZoomVertMouseSensitivity", $pref::Input::ZoomVertMouseSensitivity); %option-->nameText.setText("Zoom Vertical Sensitivity"); %option = OptionsMenu.addSliderOption(CameraMenuOptionsArray, "0.1 1", 8, "$pref::Input::ZoomHorzMouseSensitivity", $pref::Input::ZoomHorzMouseSensitivity); %option-->nameText.setText("Zoom Horizontal Sensitivity"); %option = OptionsMenu.addSliderOption(CameraMenuOptionsArray, "65 90", 25, "$pref::Player::defaultFov", $pref::Player::defaultFov, FOVOptionSlider); %option-->nameText.setText("Field of View"); CameraMenuOptionsArray.refresh(); } function CameraMenuOKButton::onClick(%this) { //save the settings and then back out CameraMenu.apply(); OptionsMenu.backOut(); } function CameraMenuDefaultsButton::onClick(%this) { } // ============================================================================= // AUDIO MENU // ============================================================================= $AudioTestHandle = 0; // Description to use for playing the volume test sound. This isn't // played with the description of the channel that has its volume changed // because we know nothing about the playback state of the channel. If it // is paused or stopped, the test sound would not play then. $AudioTestDescription = new SFXDescription() { sourceGroup = AudioChannelMaster; }; function AudioMenu::loadSettings(%this) { // Audio //OptAudioHardwareToggle.setStateOn($pref::SFX::useHardware); //OptAudioHardwareToggle.setActive( true ); %this-->OptAudioVolumeMaster.setValue( $pref::SFX::masterVolume ); %this-->OptAudioVolumeShell.setValue( $pref::SFX::channelVolume[ $GuiAudioType] ); %this-->OptAudioVolumeSim.setValue( $pref::SFX::channelVolume[ $SimAudioType ] ); %this-->OptAudioVolumeMusic.setValue( $pref::SFX::channelVolume[ $MusicAudioType ] ); AudioMenuSoundDriver.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); if ( AudioMenuSoundDriver.findText( %provider ) == -1 ) AudioMenuSoundDriver.add( %provider, %i ); } AudioMenuSoundDriver.sort(); %selId = AudioMenuSoundDriver.findText($pref::SFX::provider); if ( %selId == -1 ) AudioMenuSoundDriver.setFirstSelected(); else AudioMenuSoundDriver.setSelected( %selId ); } function AudioMenu::loadDevices(%this) { if(!isObject(SoundDeviceGroup)) { new SimGroup( SoundDeviceGroup ); } else { SoundDeviceGroup.clear(); } %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for (%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); %device = getField(%record, 1); if($pref::SFX::provider !$= %provider) continue; %setting = new ArrayObject() { class = "OptionsMenuSettingLevel"; caseSensitive = true; displayName = %device; key["$pref::SFX::Device"] = %device; }; SoundDeviceGroup.add(%setting); } } function AudioMenu::apply(%this) { sfxSetMasterVolume( $pref::SFX::masterVolume ); sfxSetChannelVolume( $GuiAudioType, $pref::SFX::channelVolume[ $GuiAudioType ] ); sfxSetChannelVolume( $SimAudioType, $pref::SFX::channelVolume[ $SimAudioType ] ); sfxSetChannelVolume( $MusicAudioType, $pref::SFX::channelVolume[ $MusicAudioType ] ); if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1 ) ) error( "Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware ); if( !isObject( $AudioTestHandle ) ) { sfxPlay(menuButtonPressed); } } function AudioMenuOKButton::onClick(%this) { //save the settings and then back out AudioMenu.apply(); OptionsMenu.backOut(); } function AudioMenuDefaultsButton::onClick(%this) { sfxInit(); AudioMenu.loadSettings(); } function OptAudioUpdateMasterVolume( %volume ) { if( %volume == $pref::SFX::masterVolume ) return; sfxSetMasterVolume( %volume ); $pref::SFX::masterVolume = %volume; if( !isObject( $AudioTestHandle ) ) $AudioTestHandle = sfxPlayOnce( AudioChannel, "art/sound/ui/volumeTest.wav" ); } function OptAudioUpdateChannelVolume( %description, %volume ) { %channel = sfxGroupToOldChannel( %description.sourceGroup ); if( %volume == $pref::SFX::channelVolume[ %channel ] ) return; sfxSetChannelVolume( %channel, %volume ); $pref::SFX::channelVolume[ %channel ] = %volume; if( !isObject( $AudioTestHandle ) ) { $AudioTestDescription.volume = %volume; $AudioTestHandle = sfxPlayOnce( $AudioTestDescription, "art/sound/ui/volumeTest.wav" ); } } function AudioMenuSoundDriver::onSelect( %this, %id, %text ) { // Skip empty provider selections. if ( %text $= "" ) return; $pref::SFX::provider = %text; AudioMenuSoundDevice.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); %device = getField(%record, 1); if (%provider !$= %text) continue; if ( AudioMenuSoundDevice.findText( %device ) == -1 ) AudioMenuSoundDevice.add( %device, %i ); } // Find the previous selected device. %selId = AudioMenuSoundDevice.findText($pref::SFX::device); if ( %selId == -1 ) AudioMenuSoundDevice.setFirstSelected(); else AudioMenuSoundDevice.setSelected( %selId ); } function AudioMenuSoundDevice::onSelect( %this, %id, %text ) { // Skip empty selections. if ( %text $= "" ) return; $pref::SFX::device = %text; if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1 ) ) error( "Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware ); }
// // Sharpener.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // Ruben Vermeersch <ruben@savanne.be> // // Copyright (C) 2009-2010 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // Copyright (C) 2010 Ruben Vermeersch // // 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 Gtk; using Mono.Unix; using FSpot.UI.Dialog; using Hyena.Widgets; namespace FSpot.Widgets { public class Sharpener : Loupe { Gtk.SpinButton amount_spin = new Gtk.SpinButton (0.5, 100.0, .01); Gtk.SpinButton radius_spin = new Gtk.SpinButton (5.0, 50.0, .01); Gtk.SpinButton threshold_spin = new Gtk.SpinButton (0.0, 50.0, .01); Gtk.Dialog dialog; ThreadProgressDialog progressDialog; bool okClicked; public Sharpener (PhotoImageView view) : base (view) { } protected override void UpdateSample () { if (!okClicked) { base.UpdateSample (); if (overlay != null) overlay.Dispose (); overlay = null; if (source != null) overlay = PixbufUtils.UnsharpMask (source, radius_spin.Value, amount_spin.Value, threshold_spin.Value, null); } } void HandleSettingsChanged (object sender, EventArgs args) { UpdateSample (); } public void doSharpening () { progressDialog.Fraction = 0.0; // FIXME: This should probably be translated progressDialog.Message = "Photo is being sharpened"; okClicked = true; Photo photo = view.Item.Current as Photo; if (photo == null) return; try { Gdk.Pixbuf orig = view.Pixbuf; Gdk.Pixbuf final = PixbufUtils.UnsharpMask (orig, radius_spin.Value, amount_spin.Value, threshold_spin.Value, progressDialog); bool create_version = photo.DefaultVersion.IsProtected; photo.SaveVersion (final, create_version); photo.Changes.DataChanged = true; App.Instance.Database.Photos.Commit (photo); } catch (Exception e) { string msg = Catalog.GetString ("Error saving sharpened photo"); string desc = string.Format (Catalog.GetString ("Received exception \"{0}\". Unable to save photo {1}"), e.Message, photo.Name); HigMessageDialog md = new HigMessageDialog (this, DialogFlags.DestroyWithParent, Gtk.MessageType.Error, ButtonsType.Ok, msg, desc); md.Run (); md.Destroy (); } progressDialog.Fraction = 1.0; // FIXME: This should probably be translated progressDialog.Message = "Sharpening complete!"; progressDialog.ButtonLabel = Gtk.Stock.Ok; Destroy (); } void HandleOkClicked (object sender, EventArgs args) { Hide (); dialog.Hide (); System.Threading.Thread command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (doSharpening)); command_thread.Name = "Sharpening"; progressDialog = new ThreadProgressDialog (command_thread, 1); progressDialog.Start (); } public void HandleCancelClicked (object sender, EventArgs args) { Destroy (); } public void HandleLoupeDestroyed (object sender, EventArgs args) { dialog.Destroy (); } protected override void BuildUI () { base.BuildUI (); string title = Catalog.GetString ("Sharpen"); dialog = new Gtk.Dialog (title, (Gtk.Window)this, DialogFlags.DestroyWithParent, new object [0]); dialog.BorderWidth = 12; dialog.VBox.Spacing = 6; Gtk.Table table = new Gtk.Table (3, 2, false); table.ColumnSpacing = 6; table.RowSpacing = 6; table.Attach (SetFancyStyle (new Gtk.Label (Catalog.GetString ("Amount:"))), 0, 1, 0, 1); table.Attach (SetFancyStyle (new Gtk.Label (Catalog.GetString ("Radius:"))), 0, 1, 1, 2); table.Attach (SetFancyStyle (new Gtk.Label (Catalog.GetString ("Threshold:"))), 0, 1, 2, 3); SetFancyStyle (amount_spin = new Gtk.SpinButton (0.00, 100.0, .01)); SetFancyStyle (radius_spin = new Gtk.SpinButton (1.0, 50.0, .01)); SetFancyStyle (threshold_spin = new Gtk.SpinButton (0.0, 50.0, .01)); amount_spin.Value = .5; radius_spin.Value = 5; threshold_spin.Value = 0.0; amount_spin.ValueChanged += HandleSettingsChanged; radius_spin.ValueChanged += HandleSettingsChanged; threshold_spin.ValueChanged += HandleSettingsChanged; table.Attach (amount_spin, 1, 2, 0, 1); table.Attach (radius_spin, 1, 2, 1, 2); table.Attach (threshold_spin, 1, 2, 2, 3); Gtk.Button cancel_button = new Gtk.Button (Gtk.Stock.Cancel); cancel_button.Clicked += HandleCancelClicked; dialog.AddActionWidget (cancel_button, Gtk.ResponseType.Cancel); Gtk.Button ok_button = new Gtk.Button (Gtk.Stock.Ok); ok_button.Clicked += HandleOkClicked; dialog.AddActionWidget (ok_button, Gtk.ResponseType.Cancel); dialog.DeleteEvent += HandleCancelClicked; Destroyed += HandleLoupeDestroyed; table.ShowAll (); dialog.VBox.PackStart (table); dialog.ShowAll (); } void HandleDeleteEvent (object o, DeleteEventArgs args) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Contentful.Core.Models; using Contentful.Core.Models.Management; [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly:InternalsVisibleTo("Forte.ContentfulSchema.Tests")] namespace Forte.ContentfulSchema.Core { public class ContentTypeDefinition { public ContentType InferredContentType { get; } public EditorInterface InferredEditorInterface { get; } public ContentTypeDefinition(ContentType inferredContentType, EditorInterface inferredEditorInterface) { InferredContentType = inferredContentType; InferredEditorInterface = inferredEditorInterface; } public bool Update(ContentType contentType) { var modified = false; if (InferredContentType.SystemProperties.Id != contentType.SystemProperties.Id) { contentType.SystemProperties.Id = InferredContentType.SystemProperties.Id; modified = true; } if (InferredContentType.Name != contentType.Name) { contentType.Name = InferredContentType.Name; modified = true; } if (AreEmptyOrEqual(InferredContentType.Description, contentType.Description) == false) { contentType.Description = InferredContentType.Description; modified = true; } if (AreEmptyOrEqual(InferredContentType.DisplayField, contentType.DisplayField) == false) { contentType.DisplayField = InferredContentType.DisplayField; modified = true; } var matchedExistingFields = contentType.Fields.GroupJoin( InferredContentType.Fields, field => field.Id, field => field.Id, (field, fields) => new {Existing = field, Updated = fields.SingleOrDefault()}); var matchedNewFields = InferredContentType.Fields.GroupJoin( contentType.Fields, field => field.Id, field => field.Id, (field, fields) => new {Existing = fields.SingleOrDefault(), Updated = field}); foreach (var match in matchedExistingFields.Union(matchedNewFields).ToList()) { if (match.Updated == null) { if (match.Existing.Disabled == false) { match.Existing.Disabled = true; modified = true; } } else if (match.Existing == null) { contentType.Fields.Add(match.Updated); modified = true; } else { UpdateField(match.Existing, match.Updated, ref modified); } } var disabledContentTypeFields = contentType.Fields.Where(field => field.Disabled).ToList(); var enabledContentTypeFields = contentType.Fields.Where(field => field.Disabled == false).ToList(); var inferredContentTypeFields = InferredContentType.Fields; if (inferredContentTypeFields.Count == enabledContentTypeFields.Count) { for (var i = 0; i < inferredContentTypeFields.Count; i++) { if (inferredContentTypeFields[i]?.Id != enabledContentTypeFields[i]?.Id) // order has changed { modified = true; //update order contentType.Fields = inferredContentTypeFields.Union(disabledContentTypeFields).ToList(); break; } } } return modified; } public bool Update(EditorInterface editorInterface) { // // Cannot add or remove controls (they always have to match content type fields) - use Join not GroupJoin // var matchedControls = editorInterface.Controls.Join(InferredEditorInterface.Controls, infered => infered.FieldId, existing => existing.FieldId, (i, e) => new { Existing = i, Updated = e}); var modified = false; foreach (var match in matchedControls) { if (string.IsNullOrEmpty(match.Updated.WidgetId) == false && match.Existing.WidgetId != match.Updated.WidgetId) { match.Existing.WidgetId = match.Updated.WidgetId; modified = true; } } return modified; } private void UpdateField(Field existing, Field updated, ref bool modified) { if (existing.Name != updated.Name) { existing.Name = updated.Name; modified = true; } if (existing.Type != updated.Type) { existing.Type = updated.Type; modified = true; } if (existing.Disabled != updated.Disabled) { existing.Disabled = updated.Disabled; modified = true; } if (existing.Omitted != updated.Omitted) { existing.Omitted = updated.Omitted; modified = true; } if (existing.Localized != updated.Localized) { existing.Localized = updated.Localized; modified = true; } if (existing.Required != updated.Required) { existing.Required = updated.Required; modified = true; } if (existing.LinkType != updated.LinkType) { existing.LinkType = updated.LinkType; modified = true; } if (Equals(existing.Validations, updated.Validations) == false) { existing.Validations = updated.Validations; modified = true; } if (existing.Items == null && updated.Items != null) { existing.Items = updated.Items; modified = true; } else if (existing.Items != null && updated.Items == null) { existing.Items = null; modified = true; } else if (existing.Items != null && updated.Items != null) { if (existing.Items.LinkType != updated.Items.LinkType) { existing.Items.LinkType = updated.Items.LinkType; modified = true; } if (existing.Items.Type != updated.Items.Type) { existing.Items.Type = updated.Items.Type; modified = true; } if (Equals(existing.Items.Validations, updated.Items.Validations) == false) { existing.Items.Validations = updated.Items.Validations; modified = true; } } } private static bool Equals(IEnumerable<IFieldValidator> first, IEnumerable<IFieldValidator> second) { if (first == null && second == null) return true; if (first == null || second == null) return false; if (first.Count() != second.Count()) return false; foreach (var validator in first) { var match = second.FirstOrDefault(v => v.GetType() == validator.GetType()); if (match == null) return false; switch (validator) { case LinkContentTypeValidator linkTypeValidator: if (Equals(linkTypeValidator, (LinkContentTypeValidator) match) == false) return false; break; default: return false; } } return true; } private static bool Equals(LinkContentTypeValidator first, LinkContentTypeValidator second) { if (AreEmptyOrEqual(first.Message, second.Message) == false) return false; if (first.ContentTypeIds.SequenceEqual(second.ContentTypeIds) == false) return false; return true; } private static bool AreEmptyOrEqual(string a, string b) { if (String.IsNullOrEmpty(a) && String.IsNullOrEmpty(b)) return true; return a == b; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Threading; using Java.Util.Concurrent.Helpers; namespace Java.Util.Concurrent { /// <summary> /// An unbounded <see cref="IBlockingQueue{T}"/> of <see cref="IDelayed"/> /// elements, in which an element can only be taken when its delay has expired. /// </summary> /// <remarks> /// <para> /// The <b>head</b> of the queue is that <see cref="IDelayed"/> element whose /// delay expired furthest in the past. If no delay has expired there is no /// head and <see cref="Poll(out T)"/> will return <c>false</c>. Expiration /// occurs when an element's <see cref="IDelayed.GetRemainingDelay"/> method /// returns a value less then or equals to zero. Even though unexpired elements /// cannot be removed using <see cref="Take"/> or <see cref="Poll(out T)"/>, /// they are otherwise treated as normal elements. For example, the /// <see cref="Count"/> property returns the count of both expired and unexpired /// elements. This queue does not permit <c>null</c> elements. /// </para> /// <para> /// This class implement all of the <i>optional</i> methods of the /// <see cref="ICollection{T}"/> interfaces. /// </para> /// </remarks> /// <typeparam name="T"> /// The type of elements that implements <see cref="IDelayed"/>. /// </typeparam> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> [Serializable] public class DelayQueue<T> : AbstractBlockingQueue<T>, IDeserializationCallback // BACKPORT_3_1 where T : IDelayed { [NonSerialized] private object _lock = new object(); private readonly PriorityQueue<T> _queue; /// <summary> /// Creates a new, empty <see cref="DelayQueue{T}"/>. /// </summary> public DelayQueue() { _queue = new PriorityQueue<T>(); } /// <summary> /// Creates a <see cref="DelayQueue{T}"/> initially containing the /// elements of the given collection of <see cref="IDelayed"/> /// instances specified by parameter <paramref name="source"/>. /// </summary> /// <param name="source"> /// Collection of elements to populate queue with. /// </param> /// <exception cref="ArgumentNullException"> /// If the collection is <c>null</c>. /// </exception> /// <exception cref="NullReferenceException"> /// If any of the elements of the collection are <c>null</c>. /// </exception> public DelayQueue(IEnumerable<T> source) { _queue = new PriorityQueue<T>(source); } /// <summary> /// Returns the capacity of this queue. Since this is a unbounded queue, <see cref="int.MaxValue"/> is returned. /// </summary> public override int Capacity { get { return Int32.MaxValue; } } /// <summary> /// <see cref="DelayQueue{T}"/> is unbounded so this always /// return <see cref="int.MaxValue"/>. /// </summary> /// <returns><see cref="int.MaxValue"/></returns> public override int RemainingCapacity { get { return Int32.MaxValue; } } /// <summary> /// Inserts the specified element into this delay queue. /// </summary> /// <param name="element">The element to add.</param> /// <returns>Always <c>true</c></returns> /// <exception cref="NullReferenceException"> /// If the specified element is <c>null</c>. /// </exception> public override bool Offer(T element) { lock (_lock) { T first; bool emptyBeforeOffer = !_queue.Peek(out first); _queue.Offer(element); if (emptyBeforeOffer || element.CompareTo(first) < 0) { Monitor.PulseAll(_lock); } return true; } } /// <summary> /// Inserts the specified element into this delay queue. As the queue is /// unbounded this method will never block. /// </summary> /// <param name="element">Element to add.</param> /// <exception cref="NullReferenceException"> /// If the element is <c>null</c>. /// </exception> public override void Put(T element) { Offer(element); } /// <summary> /// Inserts the specified element into this delay queue. As the queue /// is unbounded this method will never block. /// </summary> /// <param name="element">The element to add.</param> /// <param name="duration"> /// This parameter is ignored as this method never blocks. /// </param> /// <returns>Always <c>true</c>.</returns> /// <exception cref="ArgumentNullException"> /// If the specified element is <c>null</c>. /// </exception> public override bool Offer(T element, TimeSpan duration) { return Offer(element); } /// <summary> /// Retrieves and removes the head of this queue, or returns /// <c>false</c> if this has queue no elements with an expired delay. /// </summary> /// <param name="element"> /// Set to the elemented retrieved from the queue if the return value /// is <c>true</c>. Otherwise, set to <c>default(T)</c>. /// </param> /// <returns> /// <c>false</c> if this queue has no elements with an expired delay. /// Otherwise <c>true</c>. /// </returns> public override bool Poll(out T element) { lock (_lock) { T first; if (!_queue.Peek(out first) || first.GetRemainingDelay().Ticks > 0) { element = default(T); return false; } T x; bool hasOne = _queue.Poll(out x); Debug.Assert(hasOne); if (_queue.Count != 0) { Monitor.PulseAll(_lock); } element = x; return true; } } /// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element with an expired delay is available on this queue. /// </summary> /// <returns>The head of this queue.</returns> /// <exception cref="ThreadInterruptedException"> /// If thread is interruped when waiting. /// </exception> public override T Take() { lock (_lock) { for (; ; ) { T first; if (!_queue.Peek(out first)) { Monitor.Wait(_lock); } else { TimeSpan delay = first.GetRemainingDelay(); if (delay.Ticks > 0) { Monitor.Wait(_lock, delay); } else { T x; bool hasOne = _queue.Poll(out x); Debug.Assert(hasOne); if (_queue.Count != 0) { Monitor.PulseAll(_lock); } return x; } } } } } /// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element with an expired delay is available on this queue, /// or the specified wait time expires. /// </summary> /// <param name="duration">How long to wait before giving up.</param> /// <param name="element"> /// Set to the head of this queue, or <c>default(T)</c> if the specified /// waiting time elapses before an element with an expired delay becomes /// available /// </param> /// <returns> /// <c>false</c> if the specified waiting time elapses before an element /// is available. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { lock (_lock) { DateTime deadline = WaitTime.Deadline(duration); for (; ; ) { T first; if (!_queue.Peek(out first)) { if (duration.Ticks <= 0) { element = default(T); return false; } Monitor.Wait(_lock, WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } else { TimeSpan delay = first.GetRemainingDelay(); if (delay.Ticks > 0) { if (duration.Ticks <= 0) { element = default(T); return false; } if (delay > duration) { delay = duration; } Monitor.Wait(_lock, WaitTime.Cap(delay)); duration = deadline.Subtract(DateTime.UtcNow); } else { T x; bool hasOne = _queue.Poll(out x); Debug.Assert(hasOne); if (_queue.Count != 0) { Monitor.PulseAll(_lock); } element = x; return true; } } } } } /// <summary> /// Retrieves, but does not remove, the head of this queue into out /// parameter <paramref name="element"/>. Unlike <see cref="Poll(out T)"/>, /// if no expired elements are available in the queue, this method returns /// the element that will expire next, if one exists. /// </summary> /// <param name="element"> /// The head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <returns> /// <c>false</c> is the queue is empty. Otherwise <c>true</c>. /// </returns> public override bool Peek(out T element) { lock (_lock) { return _queue.Peek(out element); } } /// <summary> /// Does the real work for all drain methods. Caller must /// guarantee the <paramref name="action"/> is not <c>null</c> and /// <paramref name="maxElements"/> is greater then zero (0). /// </summary> /// <seealso cref="IQueue{T}.Drain(System.Action{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/> internal protected override int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria) { lock (_lock) { int n = _queue.Drain(action, maxElements, criteria, (e => e.GetRemainingDelay().Ticks > 0) ); if (n > 0) { Monitor.PulseAll(_lock); } return n; } } #region ICollection Members /// <summary> /// Returns the current number of elements in this queue. /// </summary> public override int Count { get { lock (_lock) { return _queue.Count; } } } /// <summary> /// Returns an enumerator over all the elements (both expired and /// unexpired) in this queue. The enumerator does not return the /// elements in any particular order. /// </summary> /// <remarks> /// The returned <see cref="IEnumerator{T}"/> is a "weakly consistent" /// enumerator that will not throw <see cref="InvalidOperationException"/> /// when the queue is concurrently modified, and guarantees to traverse /// elements as they existed upon construction of the enumerator, and /// may (but is not guaranteed to) reflect any modifications subsequent /// to construction. /// </remarks> /// <returns> /// An enumerator over the elements in this queue. /// </returns> public override IEnumerator<T> GetEnumerator() { return new ToArrayEnumerator<T>(_queue); } /// <summary> /// When implemented by a class, copies the elements of the ICollection to an Array, starting at a particular Array index. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing.</param> /// <param name="index">The zero-based index in array at which copying begins. </param> protected override void CopyTo(Array array, int index) { lock (_lock) { ((ICollection)_queue).CopyTo(array, index); } } /// <summary> /// Does the actual work of copying to array. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the /// destination of the elements copied from <see cref="ICollection{T}"/>. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in array at which copying begins. /// </param> /// <param name="ensureCapacity"> /// If is <c>true</c>, calls <see cref="AbstractCollection{T}.EnsureCapacity"/> /// </param> /// <returns> /// A new array of same runtime type as <paramref name="array"/> if /// <paramref name="array"/> is too small to hold all elements and /// <paramref name="ensureCapacity"/> is <c>false</c>. Otherwise /// the <paramref name="array"/> instance itself. /// </returns> protected override T[] DoCopyTo(T[] array, int arrayIndex, bool ensureCapacity) { lock (_lock) { if (ensureCapacity) array = EnsureCapacity(array, Count); _queue.CopyTo(array, arrayIndex); return array; } } /// <summary> /// Removes all of the elements from this queue. /// </summary> /// <remarks> /// <para> /// The queue will be empty after this call returns. /// </para> /// </remarks> public override void Clear() { lock (_lock) { _queue.Clear(); } } /// <summary> /// Removes a single instance of the specified element from this /// queue, if it is present, whether or not it has expired. /// </summary> /// <param name="element">element to remove</param> /// <returns><c>true</c> if element was remove, <c>false</c> if not.</returns> public override bool Remove(T element) { lock (_lock) { return _queue.Remove(element); } } #endregion #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) { _lock = new object(); } #endregion } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Lucene.Net.Analysis.Tokenattributes; using Version = Lucene.Net.Util.Version; namespace Lucene.Net.Analysis.Miscellaneous { /* * Efficient Lucene analyzer/tokenizer that preferably operates on a String rather than a * {@link java.io.Reader}, that can flexibly separate text into terms via a regular expression {@link Regex} * (with behaviour identical to {@link String#split(String)}), * and that combines the functionality of * {@link org.apache.lucene.analysis.LetterTokenizer}, * {@link org.apache.lucene.analysis.LowerCaseTokenizer}, * {@link org.apache.lucene.analysis.WhitespaceTokenizer}, * {@link org.apache.lucene.analysis.StopFilter} into a single efficient * multi-purpose class. * <p> * If you are unsure how exactly a regular expression should look like, consider * prototyping by simply trying various expressions on some test texts via * {@link String#split(String)}. Once you are satisfied, give that regex to * RegexAnalyzer. Also see <a target="_blank" * href="http://java.sun.com/docs/books/tutorial/extra/regex/">Java Regular Expression Tutorial</a>. * <p> * This class can be considerably faster than the "normal" Lucene tokenizers. * It can also serve as a building block in a compound Lucene * {@link org.apache.lucene.analysis.TokenFilter} chain. For example as in this * stemming example: * <pre> * RegexAnalyzer pat = ... * TokenStream tokenStream = new SnowballFilter( * pat.tokenStream("content", "James is running round in the woods"), * "English")); * </pre> * */ public class PatternAnalyzer : Analyzer { /* <c>"\\W+"</c>; Divides text at non-letters (NOT char.IsLetter(c)) */ public static readonly Regex NON_WORD_PATTERN = new Regex("\\W+", RegexOptions.Compiled); /* <c>"\\s+"</c>; Divides text at whitespaces (char.IsWhitespace(c)) */ public static readonly Regex WHITESPACE_PATTERN = new Regex("\\s+", RegexOptions.Compiled); private static readonly CharArraySet EXTENDED_ENGLISH_STOP_WORDS = CharArraySet.UnmodifiableSet(new CharArraySet((IEnumerable<string>)new[]{ "a", "about", "above", "across", "adj", "after", "afterwards", "again", "against", "albeit", "all", "almost", "alone", "along", "already", "also", "although", "always", "among", "amongst", "an", "and", "another", "any", "anyhow", "anyone", "anything", "anywhere", "are", "around", "as", "at", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "both", "but", "by", "can", "cannot", "co", "could", "down", "during", "each", "eg", "either", "else", "elsewhere", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "first", "for", "former", "formerly", "from", "further", "had", "has", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "i", "ie", "if", "in", "inc", "indeed", "into", "is", "it", "its", "itself", "last", "latter", "latterly", "least", "less", "ltd", "many", "may", "me", "meanwhile", "might", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "namely", "neither", "never", "nevertheless", "next", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own", "per", "perhaps", "rather", "s", "same", "seem", "seemed", "seeming", "seems", "several", "she", "should", "since", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "t", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefor", "therein", "thereupon", "these", "they", "this", "those", "though", "through", "throughout", "thru", "thus", "to", "together", "too", "toward", "towards", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "whatsoever", "when", "whence", "whenever", "whensoever", "where", "whereafter", "whereas", "whereat", "whereby", "wherefrom", "wherein", "whereinto", "whereof", "whereon", "whereto", "whereunto", "whereupon", "wherever", "wherewith", "whether", "which", "whichever", "whichsoever", "while", "whilst", "whither", "who", "whoever", "whole", "whom", "whomever", "whomsoever", "whose", "whosoever", "why", "will", "with", "within", "without", "would", "xsubj", "xcal", "xauthor", "xother ", "xnote", "yet", "you", "your", "yours", "yourself", "yourselves" }, true)); /* * A lower-casing word analyzer with English stop words (can be shared * freely across threads without harm); global per class loader. */ public static readonly PatternAnalyzer DEFAULT_ANALYZER = new PatternAnalyzer( Version.LUCENE_CURRENT, NON_WORD_PATTERN, true, StopAnalyzer.ENGLISH_STOP_WORDS_SET); /* * A lower-casing word analyzer with <b>extended </b> English stop words * (can be shared freely across threads without harm); global per class * loader. The stop words are borrowed from * http://thomas.loc.gov/home/stopwords.html, see * http://thomas.loc.gov/home/all.about.inquery.html */ public static readonly PatternAnalyzer EXTENDED_ANALYZER = new PatternAnalyzer( Version.LUCENE_CURRENT, NON_WORD_PATTERN, true, EXTENDED_ENGLISH_STOP_WORDS); private readonly Regex Regex; private readonly bool toLowerCase; private readonly ISet<string> stopWords; private readonly Version matchVersion; /* * Constructs a new instance with the given parameters. * * @param matchVersion If >= {@link Version#LUCENE_29}, StopFilter.enablePositionIncrement is set to true * @param Regex * a regular expression delimiting tokens * @param toLowerCase * if <c>true</c> returns tokens after applying * String.toLowerCase() * @param stopWords * if non-null, ignores all tokens that are contained in the * given stop set (after previously having applied toLowerCase() * if applicable). For example, created via * {@link StopFilter#makeStopSet(String[])}and/or * {@link org.apache.lucene.analysis.WordlistLoader}as in * <c>WordlistLoader.getWordSet(new File("samples/fulltext/stopwords.txt")</c> * or <a href="http://www.unine.ch/info/clef/">other stop words * lists </a>. */ public PatternAnalyzer(Version matchVersion, Regex Regex, bool toLowerCase, ISet<string> stopWords) { if (Regex == null) throw new ArgumentException("Regex must not be null"); if (EqRegex(NON_WORD_PATTERN, Regex)) Regex = NON_WORD_PATTERN; else if (EqRegex(WHITESPACE_PATTERN, Regex)) Regex = WHITESPACE_PATTERN; if (stopWords != null && stopWords.Count == 0) stopWords = null; this.Regex = Regex; this.toLowerCase = toLowerCase; this.stopWords = stopWords; this.matchVersion = matchVersion; } /* * Creates a token stream that tokenizes the given string into token terms * (aka words). * * @param fieldName * the name of the field to tokenize (currently ignored). * @param text * the string to tokenize * @return a new token stream */ public TokenStream TokenStream(String fieldName, String text) { // Ideally the Analyzer superclass should have a method with the same signature, // with a default impl that simply delegates to the StringReader flavour. if (text == null) throw new ArgumentException("text must not be null"); TokenStream stream; if (Regex == NON_WORD_PATTERN) { // fast path stream = new FastStringTokenizer(text, true, toLowerCase, stopWords); } else if (Regex == WHITESPACE_PATTERN) { // fast path stream = new FastStringTokenizer(text, false, toLowerCase, stopWords); } else { stream = new RegexTokenizer(text, Regex, toLowerCase); if (stopWords != null) stream = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion), stream, stopWords); } return stream; } /* * Creates a token stream that tokenizes all the text in the given Reader; * This implementation forwards to <c>tokenStream(String, String)</c> and is * less efficient than <c>tokenStream(String, String)</c>. * * @param fieldName * the name of the field to tokenize (currently ignored). * @param reader * the reader delivering the text * @return a new token stream */ public override TokenStream TokenStream(String fieldName, TextReader reader) { if (reader is FastStringReader) { // fast path return TokenStream(fieldName, ((FastStringReader)reader).GetString()); } try { String text = ToString(reader); return TokenStream(fieldName, text); } catch (IOException e) { throw new Exception("Wrapped Exception", e); } } /* * Indicates whether some other object is "equal to" this one. * * @param other * the reference object with which to compare. * @return true if equal, false otherwise */ public override bool Equals(Object other) { if (this == other) return true; if (this == DEFAULT_ANALYZER && other == EXTENDED_ANALYZER) return false; if (other == DEFAULT_ANALYZER && this == EXTENDED_ANALYZER) return false; if (other is PatternAnalyzer) { PatternAnalyzer p2 = (PatternAnalyzer)other; return toLowerCase == p2.toLowerCase && EqRegex(Regex, p2.Regex) && Eq(stopWords, p2.stopWords); } return false; } /* * Returns a hash code value for the object. * * @return the hash code. */ public override int GetHashCode() { if (this == DEFAULT_ANALYZER) return -1218418418; // fast path if (this == EXTENDED_ANALYZER) return 1303507063; // fast path int h = 1; h = 31 * h + Regex.GetHashCode(); h = 31 * h + (int)Regex.Options; h = 31 * h + (toLowerCase ? 1231 : 1237); h = 31 * h + (stopWords != null ? stopWords.GetHashCode() : 0); return h; } /* equality where o1 and/or o2 can be null */ private static bool Eq(Object o1, Object o2) { return (o1 == o2) || (o1 != null ? o1.Equals(o2) : false); } /* assumes p1 and p2 are not null */ private static bool EqRegex(Regex p1, Regex p2) { return p1 == p2 || (p1.Options == p2.Options && p1.ToString() == p2.ToString()); } /* * Reads until end-of-stream and returns all read chars, finally closes the stream. * * @param input the input stream * @throws IOException if an I/O error occurs while reading the stream */ private static String ToString(TextReader input) { try { int len = 256; char[] buffer = new char[len]; char[] output = new char[len]; len = 0; int n; while ((n = input.Read(buffer, 0, buffer.Length)) != 0) { if (len + n > output.Length) { // grow capacity char[] tmp = new char[Math.Max(output.Length << 1, len + n)]; Array.Copy(output, 0, tmp, 0, len); Array.Copy(buffer, 0, tmp, len, n); buffer = output; // use larger buffer for future larger bulk reads output = tmp; } else { Array.Copy(buffer, 0, output, len, n); } len += n; } return new String(output, 0, len); } finally { if (input != null) input.Dispose(); } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// /* * The work horse; performance isn't fantastic, but it's not nearly as bad * as one might think - kudos to the Sun regex developers. */ private sealed class RegexTokenizer : TokenStream { private readonly String str; private readonly bool toLowerCase; private Match matcher; private int pos = 0; private static readonly System.Globalization.CultureInfo locale = System.Globalization.CultureInfo.CurrentCulture; private ITermAttribute termAtt; private IOffsetAttribute offsetAtt; public RegexTokenizer(String str, Regex regex, bool toLowerCase) { this.str = str; this.matcher = regex.Match(str); this.toLowerCase = toLowerCase; this.termAtt = AddAttribute<ITermAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); } public sealed override bool IncrementToken() { if (matcher == null) return false; ClearAttributes(); while (true) { // loop takes care of leading and trailing boundary cases int start = pos; int end; bool isMatch = matcher.Success; if (isMatch) { end = matcher.Index; pos = matcher.Index + matcher.Length; matcher = matcher.NextMatch(); } else { end = str.Length; matcher = null; // we're finished } if (start != end) { // non-empty match (header/trailer) String text = str.Substring(start, end - start); if (toLowerCase) text = text.ToLower(locale); termAtt.SetTermBuffer(text); offsetAtt.SetOffset(start, end); return true; } return false; } } public override sealed void End() { // set final offset int finalOffset = str.Length; this.offsetAtt.SetOffset(finalOffset, finalOffset); } protected override void Dispose(bool disposing) { // Do Nothing } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// /* * Special-case class for best performance in common cases; this class is * otherwise unnecessary. */ private sealed class FastStringTokenizer : TokenStream { private readonly String str; private int pos; private readonly bool isLetter; private readonly bool toLowerCase; private readonly ISet<string> stopWords; private static readonly System.Globalization.CultureInfo locale = System.Globalization.CultureInfo.CurrentCulture; private ITermAttribute termAtt; private IOffsetAttribute offsetAtt; public FastStringTokenizer(String str, bool isLetter, bool toLowerCase, ISet<string> stopWords) { this.str = str; this.isLetter = isLetter; this.toLowerCase = toLowerCase; this.stopWords = stopWords; this.termAtt = AddAttribute<ITermAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); } public override bool IncrementToken() { ClearAttributes(); // cache loop instance vars (performance) String s = str; int len = s.Length; int i = pos; bool letter = isLetter; int start = 0; String text; do { // find beginning of token text = null; while (i < len && !IsTokenChar(s[i], letter)) { i++; } if (i < len) { // found beginning; now find end of token start = i; while (i < len && IsTokenChar(s[i], letter)) { i++; } text = s.Substring(start, i - start); if (toLowerCase) text = text.ToLower(locale); // if (toLowerCase) { //// use next line once JDK 1.5 String.toLowerCase() performance regression is fixed //// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265809 // text = s.substring(start, i).toLowerCase(); //// char[] chars = new char[i-start]; //// for (int j=start; j < i; j++) chars[j-start] = char.toLowerCase(s[j] ); //// text = new String(chars); // } else { // text = s.substring(start, i); // } } } while (text != null && IsStopWord(text)); pos = i; if (text == null) { return false; } termAtt.SetTermBuffer(text); offsetAtt.SetOffset(start, i); return true; } public override sealed void End() { // set final offset int finalOffset = str.Length; this.offsetAtt.SetOffset(finalOffset, finalOffset); } protected override void Dispose(bool disposing) { // Do Nothing } private bool IsTokenChar(char c, bool isLetter) { return isLetter ? char.IsLetter(c) : !char.IsWhiteSpace(c); } private bool IsStopWord(string text) { return stopWords != null && stopWords.Contains(text); } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// /* * A StringReader that exposes it's contained string for fast direct access. * Might make sense to generalize this to CharSequence and make it public? */ internal sealed class FastStringReader : StringReader { private readonly string s; protected internal FastStringReader(string s) : base(s) { this.s = s; } internal string GetString() { return s; } } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace DocuSign.eSign.Model { /// <summary> /// /// </summary> [DataContract] public class LoginAccount : IEquatable<LoginAccount> { /// <summary> /// The name associated with the account. /// </summary> /// <value>The name associated with the account.</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// The account ID associated with the envelope. /// </summary> /// <value>The account ID associated with the envelope.</value> [DataMember(Name="accountId", EmitDefaultValue=false)] public string AccountId { get; set; } /// <summary> /// The GUID associated with the account ID. /// </summary> /// <value>The GUID associated with the account ID.</value> [DataMember(Name="accountIdGuid", EmitDefaultValue=false)] public string AccountIdGuid { get; set; } /// <summary> /// The URL that should be used for successive calls to this account. It includes the protocal (https), the DocuSign server where the account is located, and the account number. Use this Url to make API calls against this account. Many of the API calls provide Uri's that are relative to this baseUrl. /// </summary> /// <value>The URL that should be used for successive calls to this account. It includes the protocal (https), the DocuSign server where the account is located, and the account number. Use this Url to make API calls against this account. Many of the API calls provide Uri's that are relative to this baseUrl.</value> [DataMember(Name="baseUrl", EmitDefaultValue=false)] public string BaseUrl { get; set; } /// <summary> /// This value is true if this is the default account for the user, otherwise false is returned. /// </summary> /// <value>This value is true if this is the default account for the user, otherwise false is returned.</value> [DataMember(Name="isDefault", EmitDefaultValue=false)] public string IsDefault { get; set; } /// <summary> /// The name of this user as defined by the account. /// </summary> /// <value>The name of this user as defined by the account.</value> [DataMember(Name="userName", EmitDefaultValue=false)] public string UserName { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="userId", EmitDefaultValue=false)] public string UserId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// An optional descirption of the site that hosts the account. /// </summary> /// <value>An optional descirption of the site that hosts the account.</value> [DataMember(Name="siteDescription", EmitDefaultValue=false)] public string SiteDescription { get; set; } /// <summary> /// A list of settings on the acccount that indicate what features are available. /// </summary> /// <value>A list of settings on the acccount that indicate what features are available.</value> [DataMember(Name="loginAccountSettings", EmitDefaultValue=false)] public List<NameValue> LoginAccountSettings { get; set; } /// <summary> /// A list of user-level settings that indicate what user-specific features are available. /// </summary> /// <value>A list of user-level settings that indicate what user-specific features are available.</value> [DataMember(Name="loginUserSettings", EmitDefaultValue=false)] public List<NameValue> LoginUserSettings { 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 LoginAccount {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AccountId: ").Append(AccountId).Append("\n"); sb.Append(" AccountIdGuid: ").Append(AccountIdGuid).Append("\n"); sb.Append(" BaseUrl: ").Append(BaseUrl).Append("\n"); sb.Append(" IsDefault: ").Append(IsDefault).Append("\n"); sb.Append(" UserName: ").Append(UserName).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" SiteDescription: ").Append(SiteDescription).Append("\n"); sb.Append(" LoginAccountSettings: ").Append(LoginAccountSettings).Append("\n"); sb.Append(" LoginUserSettings: ").Append(LoginUserSettings).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 LoginAccount); } /// <summary> /// Returns true if LoginAccount instances are equal /// </summary> /// <param name="other">Instance of LoginAccount to be compared</param> /// <returns>Boolean</returns> public bool Equals(LoginAccount other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.AccountId == other.AccountId || this.AccountId != null && this.AccountId.Equals(other.AccountId) ) && ( this.AccountIdGuid == other.AccountIdGuid || this.AccountIdGuid != null && this.AccountIdGuid.Equals(other.AccountIdGuid) ) && ( this.BaseUrl == other.BaseUrl || this.BaseUrl != null && this.BaseUrl.Equals(other.BaseUrl) ) && ( this.IsDefault == other.IsDefault || this.IsDefault != null && this.IsDefault.Equals(other.IsDefault) ) && ( this.UserName == other.UserName || this.UserName != null && this.UserName.Equals(other.UserName) ) && ( this.UserId == other.UserId || this.UserId != null && this.UserId.Equals(other.UserId) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.SiteDescription == other.SiteDescription || this.SiteDescription != null && this.SiteDescription.Equals(other.SiteDescription) ) && ( this.LoginAccountSettings == other.LoginAccountSettings || this.LoginAccountSettings != null && this.LoginAccountSettings.SequenceEqual(other.LoginAccountSettings) ) && ( this.LoginUserSettings == other.LoginUserSettings || this.LoginUserSettings != null && this.LoginUserSettings.SequenceEqual(other.LoginUserSettings) ); } /// <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.Name != null) hash = hash * 57 + this.Name.GetHashCode(); if (this.AccountId != null) hash = hash * 57 + this.AccountId.GetHashCode(); if (this.AccountIdGuid != null) hash = hash * 57 + this.AccountIdGuid.GetHashCode(); if (this.BaseUrl != null) hash = hash * 57 + this.BaseUrl.GetHashCode(); if (this.IsDefault != null) hash = hash * 57 + this.IsDefault.GetHashCode(); if (this.UserName != null) hash = hash * 57 + this.UserName.GetHashCode(); if (this.UserId != null) hash = hash * 57 + this.UserId.GetHashCode(); if (this.Email != null) hash = hash * 57 + this.Email.GetHashCode(); if (this.SiteDescription != null) hash = hash * 57 + this.SiteDescription.GetHashCode(); if (this.LoginAccountSettings != null) hash = hash * 57 + this.LoginAccountSettings.GetHashCode(); if (this.LoginUserSettings != null) hash = hash * 57 + this.LoginUserSettings.GetHashCode(); return hash; } } } }
/* * 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 OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Timers; using Timer = System.Timers.Timer; namespace OpenSim.Region.Framework.Scenes { public class KeyframeTimer { private static ThreadedClasses.RwLockedDictionary<Scene, KeyframeTimer> m_timers = new ThreadedClasses.RwLockedDictionary<Scene, KeyframeTimer>(); private Timer m_timer; private ThreadedClasses.RwLockedDictionary<KeyframeMotion, object> m_motions = new ThreadedClasses.RwLockedDictionary<KeyframeMotion, object>(); private object m_timerLock = new object(); private const double m_tickDuration = 50.0; public double TickDuration { get { return m_tickDuration; } } public KeyframeTimer(Scene scene) { m_timer = new Timer(); m_timer.Interval = TickDuration; m_timer.AutoReset = true; m_timer.Elapsed += OnTimer; } public void Start() { lock (m_timer) { if (!m_timer.Enabled) m_timer.Start(); } } private void OnTimer(object sender, ElapsedEventArgs ea) { if (!Monitor.TryEnter(m_timerLock)) return; try { foreach (KeyframeMotion m in m_motions.Keys) { try { m.OnTimer(TickDuration); } catch (Exception) { // Don't stop processing } } } catch (Exception) { // Keep running no matter what } finally { Monitor.Exit(m_timerLock); } } public static void Add(KeyframeMotion motion) { KeyframeTimer timer; if (motion.Scene == null) return; timer = m_timers.GetOrAddIfNotExists(motion.Scene, delegate() { timer = new KeyframeTimer(motion.Scene); if (!SceneManager.Instance.AllRegionsReady) { // Start the timers only once all the regions are ready. This is required // when using megaregions, because the megaregion is correctly configured // only after all the regions have been loaded. (If we don't do this then // when the prim moves it might think that it crossed into a region.) SceneManager.Instance.OnRegionsReadyStatusChange += delegate(SceneManager sm) { if (sm.AllRegionsReady) timer.Start(); }; } // Check again, in case the regions were started while we were adding the event handler if (SceneManager.Instance.AllRegionsReady) { timer.Start(); } return timer; }); timer.m_motions[motion] = null; } public static void Remove(KeyframeMotion motion) { KeyframeTimer timer; if (motion.Scene == null) return; if (m_timers.TryGetValue(motion.Scene, out timer)) { timer.m_motions.Remove(motion); } } } [Serializable] public class KeyframeMotion { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public enum PlayMode : int { Forward = 0, Reverse = 1, Loop = 2, PingPong = 3 }; [Flags] public enum DataFormat : int { Translation = 2, Rotation = 1 } [Serializable] public struct Keyframe { public Vector3? Position; public Quaternion? Rotation; public Quaternion StartRotation; public int TimeMS; public int TimeTotal; public Vector3 AngularVelocity; public Vector3 StartPosition; }; private Vector3 m_serializedPosition; private Vector3 m_basePosition; private Quaternion m_baseRotation; private Keyframe m_currentFrame; private List<Keyframe> m_frames = new List<Keyframe>(); private Keyframe[] m_keyframes; // skip timer events. //timer.stop doesn't assure there aren't event threads still being fired [NonSerialized()] private bool m_timerStopped; [NonSerialized()] private bool m_isCrossing; [NonSerialized()] private bool m_waitingCrossing; // retry position for cross fail [NonSerialized()] private Vector3 m_nextPosition; [NonSerialized()] private SceneObjectGroup m_group; private PlayMode m_mode = PlayMode.Forward; private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation; private bool m_running = false; [NonSerialized()] private bool m_selected = false; private int m_iterations = 0; private int m_skipLoops = 0; [NonSerialized()] private Scene m_scene; public Scene Scene { get { return m_scene; } } public DataFormat Data { get { return m_data; } } public bool Selected { set { if (m_group != null) { if (!value) { // Once we're let go, recompute positions if (m_selected) UpdateSceneObject(m_group); } else { // Save selection position in case we get moved if (!m_selected) { StopTimer(); m_serializedPosition = m_group.AbsolutePosition; } } } m_isCrossing = false; m_waitingCrossing = false; m_selected = value; } } private void StartTimer() { KeyframeTimer.Add(this); m_timerStopped = false; } private void StopTimer() { m_timerStopped = true; KeyframeTimer.Remove(this); } public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data) { KeyframeMotion newMotion = null; try { MemoryStream ms = new MemoryStream(data); BinaryFormatter fmt = new BinaryFormatter(); newMotion = (KeyframeMotion)fmt.Deserialize(ms); newMotion.m_group = grp; if (grp != null) { newMotion.m_scene = grp.Scene; if (grp.IsSelected) newMotion.m_selected = true; } newMotion.m_timerStopped = false; newMotion.m_running = true; newMotion.m_isCrossing = false; newMotion.m_waitingCrossing = false; } catch { newMotion = null; } return newMotion; } public void UpdateSceneObject(SceneObjectGroup grp) { m_isCrossing = false; m_waitingCrossing = false; StopTimer(); if (grp == null) return; m_group = grp; m_scene = grp.Scene; Vector3 grppos = grp.AbsolutePosition; Vector3 offset = grppos - m_serializedPosition; // avoid doing it more than once // current this will happen dragging a prim to other region m_serializedPosition = grppos; m_basePosition += offset; m_nextPosition += offset; m_currentFrame.StartPosition += offset; m_currentFrame.Position += offset; for (int i = 0; i < m_frames.Count; i++) { Keyframe k = m_frames[i]; k.StartPosition += offset; k.Position += offset; m_frames[i]=k; } if (m_running) Start(); } public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data) { m_mode = mode; m_data = data; m_group = grp; if (grp != null) { m_basePosition = grp.AbsolutePosition; m_baseRotation = grp.GroupRotation; m_scene = grp.Scene; } m_timerStopped = true; m_isCrossing = false; m_waitingCrossing = false; } public void SetKeyframes(Keyframe[] frames) { m_keyframes = frames; } public KeyframeMotion Copy(SceneObjectGroup newgrp) { StopTimer(); KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data); newmotion.m_group = newgrp; newmotion.m_scene = newgrp.Scene; if (m_keyframes != null) { newmotion.m_keyframes = new Keyframe[m_keyframes.Length]; m_keyframes.CopyTo(newmotion.m_keyframes, 0); } newmotion.m_frames = new List<Keyframe>(m_frames); newmotion.m_basePosition = m_basePosition; newmotion.m_baseRotation = m_baseRotation; if (m_selected) newmotion.m_serializedPosition = m_serializedPosition; else { if (m_group != null) newmotion.m_serializedPosition = m_group.AbsolutePosition; else newmotion.m_serializedPosition = m_serializedPosition; } newmotion.m_currentFrame = m_currentFrame; newmotion.m_iterations = m_iterations; newmotion.m_running = m_running; if (m_running && !m_waitingCrossing) StartTimer(); return newmotion; } public void Delete() { m_running = false; StopTimer(); m_isCrossing = false; m_waitingCrossing = false; m_frames.Clear(); m_keyframes = null; } public void Start() { m_isCrossing = false; m_waitingCrossing = false; if (m_keyframes != null && m_group != null && m_keyframes.Length > 0) { StartTimer(); m_running = true; } else { m_running = false; StopTimer(); } } public void Stop() { m_running = false; m_isCrossing = false; m_waitingCrossing = false; StopTimer(); m_basePosition = m_group.AbsolutePosition; m_baseRotation = m_group.GroupRotation; m_group.RootPart.Velocity = Vector3.Zero; m_group.RootPart.AngularVelocity = Vector3.Zero; m_group.SendGroupRootTerseUpdate(); // m_group.RootPart.ScheduleTerseUpdate(); m_frames.Clear(); } public void Pause() { m_running = false; StopTimer(); m_group.RootPart.Velocity = Vector3.Zero; m_group.RootPart.AngularVelocity = Vector3.Zero; m_group.SendGroupRootTerseUpdate(); // m_group.RootPart.ScheduleTerseUpdate(); } private void GetNextList() { m_frames.Clear(); Vector3 pos = m_basePosition; Quaternion rot = m_baseRotation; if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0) { int direction = 1; if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0))) direction = -1; int start = 0; int end = m_keyframes.Length; if (direction < 0) { start = m_keyframes.Length - 1; end = -1; } for (int i = start; i != end ; i += direction) { Keyframe k = m_keyframes[i]; k.StartPosition = pos; if (k.Position.HasValue) { k.Position = (k.Position * direction); // k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f); k.Position += pos; } else { k.Position = pos; // k.Velocity = Vector3.Zero; } k.StartRotation = rot; if (k.Rotation.HasValue) { if (direction == -1) k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation); k.Rotation = rot * k.Rotation; } else { k.Rotation = rot; } /* ang vel not in use for now float angle = 0; float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W; float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W; float aa_bb = aa * bb; if (aa_bb == 0) { angle = 0; } else { float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X + k.StartRotation.Y * ((Quaternion)k.Rotation).Y + k.StartRotation.Z * ((Quaternion)k.Rotation).Z + k.StartRotation.W * ((Quaternion)k.Rotation).W; float q = (ab * ab) / aa_bb; if (q > 1.0f) { angle = 0; } else { angle = (float)Math.Acos(2 * q - 1); } } k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000)); */ k.TimeTotal = k.TimeMS; m_frames.Add(k); pos = (Vector3)k.Position; rot = (Quaternion)k.Rotation; } m_basePosition = pos; m_baseRotation = rot; m_iterations++; } } public void OnTimer(double tickDuration) { if (m_skipLoops > 0) { m_skipLoops--; return; } if (m_timerStopped) // trap events still in air even after a timer.stop return; if (m_group == null) return; bool update = false; if (m_selected) { if (m_group.RootPart.Velocity != Vector3.Zero) { m_group.RootPart.Velocity = Vector3.Zero; m_group.SendGroupRootTerseUpdate(); } return; } if (m_isCrossing) { // if crossing and timer running then cross failed // wait some time then // retry to set the position that evtually caused the outbound // if still outside region this will call startCrossing below m_isCrossing = false; m_group.AbsolutePosition = m_nextPosition; if (!m_isCrossing) { StopTimer(); StartTimer(); } return; } if (m_frames.Count == 0) { GetNextList(); if (m_frames.Count == 0) { Stop(); Scene scene = m_group.Scene; IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule m in scriptModules) { if (m == null) continue; m.PostObjectEvent(m_group.RootPart.UUID, "moving_end", new object[0]); } return; } m_currentFrame = m_frames[0]; m_currentFrame.TimeMS += (int)tickDuration; //force a update on a keyframe transition update = true; } m_currentFrame.TimeMS -= (int)tickDuration; // Do the frame processing double remainingSteps = (double)m_currentFrame.TimeMS / tickDuration; if (remainingSteps <= 0.0) { m_group.RootPart.Velocity = Vector3.Zero; m_group.RootPart.AngularVelocity = Vector3.Zero; m_nextPosition = (Vector3)m_currentFrame.Position; m_group.AbsolutePosition = m_nextPosition; // we are sending imediate updates, no doing force a extra terseUpdate // m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation); m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation; m_frames.RemoveAt(0); if (m_frames.Count > 0) m_currentFrame = m_frames[0]; update = true; } else { float completed = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal; bool lastStep = m_currentFrame.TimeMS <= tickDuration; Vector3 positionThisStep = m_currentFrame.StartPosition + (m_currentFrame.Position.Value - m_currentFrame.StartPosition) * completed; Vector3 motionThisStep = positionThisStep - m_group.AbsolutePosition; float mag = Vector3.Mag(motionThisStep); if ((mag >= 0.02f) || lastStep) { m_nextPosition = m_group.AbsolutePosition + motionThisStep; m_group.AbsolutePosition = m_nextPosition; update = true; } //int totalSteps = m_currentFrame.TimeTotal / (int)tickDuration; //m_log.DebugFormat("KeyframeMotion.OnTimer: step {0}/{1}, curPosition={2}, finalPosition={3}, motionThisStep={4} (scene {5})", // totalSteps - remainingSteps + 1, totalSteps, m_group.AbsolutePosition, m_currentFrame.Position, motionThisStep, m_scene.RegionInfo.RegionName); if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation) { Quaternion current = m_group.GroupRotation; Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, completed); step.Normalize(); /* use simpler change detection * float angle = 0; float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W; float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W; float aa_bb = aa * bb; if (aa_bb == 0) { angle = 0; } else { float ab = current.X * step.X + current.Y * step.Y + current.Z * step.Z + current.W * step.W; float q = (ab * ab) / aa_bb; if (q > 1.0f) { angle = 0; } else { angle = (float)Math.Acos(2 * q - 1); } } if (angle > 0.01f) */ if(Math.Abs(step.X - current.X) > 0.001f || Math.Abs(step.Y - current.Y) > 0.001f || Math.Abs(step.Z - current.Z) > 0.001f || lastStep) // assuming w is a dependente var { // m_group.UpdateGroupRotationR(step); m_group.RootPart.RotationOffset = step; //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2); update = true; } } } if (update) { m_group.SendGroupRootTerseUpdate(); } } public Byte[] Serialize() { StopTimer(); MemoryStream ms = new MemoryStream(); BinaryFormatter fmt = new BinaryFormatter(); SceneObjectGroup tmp = m_group; m_group = null; if (!m_selected && tmp != null) m_serializedPosition = tmp.AbsolutePosition; fmt.Serialize(ms, this); m_group = tmp; if (m_running && !m_waitingCrossing) StartTimer(); return ms.ToArray(); } public void StartCrossingCheck() { // timer will be restart by crossingFailure // or never since crossing worked and this // should be deleted StopTimer(); m_isCrossing = true; m_waitingCrossing = true; // to remove / retune to smoth crossings if (m_group.RootPart.Velocity != Vector3.Zero) { m_group.RootPart.Velocity = Vector3.Zero; m_group.SendGroupRootTerseUpdate(); // m_group.RootPart.ScheduleTerseUpdate(); } } public void CrossingFailure() { m_waitingCrossing = false; if (m_group != null) { m_group.RootPart.Velocity = Vector3.Zero; m_group.SendGroupRootTerseUpdate(); // m_group.RootPart.ScheduleTerseUpdate(); if (m_running) { StopTimer(); m_skipLoops = 1200; // 60 seconds StartTimer(); } } } } }
//----------------------------------------------------------------------- // <copyright file="SplashScreenForm.Designer.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- using TQVaultAE.GUI.Properties; namespace TQVaultAE.GUI { /// <summary> /// Class for inital form which load the resources. /// </summary> internal partial class SplashScreenForm { /// <summary> /// Description label /// </summary> private ScalingLabel label3; /// <summary> /// Next button /// </summary> private ScalingButton nextButton; /// <summary> /// Exit button /// </summary> private ScalingButton exitButton; /// <summary> /// Please wait message /// </summary> private ScalingLabel labelPleaseWait; /// <summary> /// Wait timer. Used for animation of please wait message. /// </summary> private System.Timers.Timer waitTimer; /// <summary> /// Custom Progress Bar control to show the progress of the files loading. /// </summary> private VaultProgressBar progressBar; /// <summary> /// Timer for fading in and out of the form. /// </summary> private System.Windows.Forms.Timer fadeTimer; /// <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 && (this.components != null)) { this.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(SplashScreenForm)); this.label3 = new TQVaultAE.GUI.ScalingLabel(); this.nextButton = new TQVaultAE.GUI.ScalingButton(); this.exitButton = new TQVaultAE.GUI.ScalingButton(); this.labelPleaseWait = new TQVaultAE.GUI.ScalingLabel(); this.waitTimer = new System.Timers.Timer(); this.fadeTimer = new System.Windows.Forms.Timer(this.components); this.progressBar = new TQVaultAE.GUI.VaultProgressBar(); ((System.ComponentModel.ISupportInitialize)(this.waitTimer)).BeginInit(); this.SuspendLayout(); // // label3 // this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(55, 255); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(607, 54); this.label3.TabIndex = 2; this.label3.Text = "A magical place where you can store your artifacts of power that you will need to" + " save the world from the Titans."; this.label3.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // nextButton // this.nextButton.BackColor = System.Drawing.Color.Transparent; this.nextButton.DownBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonDown; this.nextButton.FlatAppearance.BorderSize = 0; this.nextButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.nextButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.nextButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.nextButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F); this.nextButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.nextButton.Image = global::TQVaultAE.GUI.Properties.Resources.MainButtonUp; this.nextButton.Location = new System.Drawing.Point(286, 365); this.nextButton.Name = "nextButton"; this.nextButton.OverBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonOver; this.nextButton.Size = new System.Drawing.Size(137, 30); this.nextButton.SizeToGraphic = false; this.nextButton.TabIndex = 3; this.nextButton.Text = "Enter The Vault"; this.nextButton.UpBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonUp; this.nextButton.UseCustomGraphic = true; this.nextButton.UseVisualStyleBackColor = false; this.nextButton.Visible = false; this.nextButton.Click += new System.EventHandler(this.NextButtonClick); // // exitButton // this.exitButton.BackColor = System.Drawing.Color.Transparent; this.exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.exitButton.DownBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonDown; this.exitButton.FlatAppearance.BorderSize = 0; this.exitButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.exitButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.exitButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.exitButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F); this.exitButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.exitButton.Image = global::TQVaultAE.GUI.Properties.Resources.MainButtonUp; this.exitButton.Location = new System.Drawing.Point(555, 420); this.exitButton.Name = "exitButton"; this.exitButton.OverBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonOver; this.exitButton.Size = new System.Drawing.Size(137, 30); this.exitButton.SizeToGraphic = false; this.exitButton.TabIndex = 4; this.exitButton.Text = "Exit"; this.exitButton.UpBitmap = global::TQVaultAE.GUI.Properties.Resources.MainButtonUp; this.exitButton.UseCustomGraphic = true; this.exitButton.UseVisualStyleBackColor = false; this.exitButton.Click += new System.EventHandler(this.ExitButtonClick); // // labelPleaseWait // this.labelPleaseWait.BackColor = System.Drawing.Color.Transparent; this.labelPleaseWait.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F); this.labelPleaseWait.ForeColor = System.Drawing.Color.Gold; this.labelPleaseWait.Location = new System.Drawing.Point(131, 318); this.labelPleaseWait.Name = "labelPleaseWait"; this.labelPleaseWait.Size = new System.Drawing.Size(457, 32); this.labelPleaseWait.TabIndex = 5; this.labelPleaseWait.Text = "Loading Game Resources...Please Wait"; this.labelPleaseWait.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // waitTimer // this.waitTimer.Enabled = true; this.waitTimer.Interval = 500D; this.waitTimer.SynchronizingObject = this; this.waitTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.WaitTimerElapsed); // // fadeTimer // this.fadeTimer.Interval = 50; this.fadeTimer.Tick += new System.EventHandler(this.FadeTimerTick); // // progressBar // this.progressBar.BackColor = System.Drawing.Color.Transparent; this.progressBar.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.progressBar.Location = new System.Drawing.Point(55, 353); this.progressBar.Maximum = 0; this.progressBar.Minimum = 0; this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(602, 58); this.progressBar.TabIndex = 7; this.progressBar.Value = 0; // // SplashScreenForm // this.AcceptButton = this.nextButton; this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackgroundImage = global::TQVaultAE.GUI.Properties.Resources.NewSplashScreen; this.CancelButton = this.exitButton; this.ClientSize = new System.Drawing.Size(716, 463); this.Controls.Add(this.labelPleaseWait); this.Controls.Add(this.exitButton); this.Controls.Add(this.nextButton); this.Controls.Add(this.label3); this.Controls.Add(this.progressBar); this.DrawCustomBorder = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SplashScreenForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Titan Quest Item Vault"; this.Click += new System.EventHandler(this.SplashScreen_Click); this.Controls.SetChildIndex(this.progressBar, 0); this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.nextButton, 0); this.Controls.SetChildIndex(this.exitButton, 0); this.Controls.SetChildIndex(this.labelPleaseWait, 0); ((System.ComponentModel.ISupportInitialize)(this.waitTimer)).EndInit(); this.ResumeLayout(false); } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 12/2/2008 9:26:55 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Data.Forms; using DotSpatial.Serialization; using DotSpatial.Symbology; using DotSpatial.Symbology.Forms; namespace DotSpatial.Controls { /// <summary> /// The legend is used to show a list of all the layers inside of Map. It describes the different categories of each layer with the help of a symbol and the categories legend text. /// </summary> [ToolboxItem(true)] public class Legend : ScrollingControl, ILegend { #region Event /// <summary> /// Occurs when the drag method is used to alter the order of layers or /// groups in the legend. /// </summary> public event EventHandler OrderChanged; /// <summary> /// Occurs when a mousedown is initiated within an existing legend item /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseDown; /// <summary> /// Occurs when a mouse down is initiated within an expand box. /// </summary> public event EventHandler<ItemMouseEventArgs> ExpandBoxMouseDown; /// <summary> /// Occurs when a mouse up is initiated within a checkbox. /// </summary> public event EventHandler<ItemMouseEventArgs> CheckBoxMouseUp; /// <summary> /// Occurs when a mouse up occurs insize of a specific item. /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseUp; /// <summary> /// Occurs when the mouse is moving over an item. /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseMove; #endregion #region Private Variables private readonly ContextMenu _contextMenu; private readonly TextBox _editBox; private readonly Icon _icoChecked; private readonly Icon _icoUnchecked; private readonly HashSet<ILegendItem> _selection; private LegendBox _dragItem; private LegendBox _dragTarget; private IColorCategory _editCategory; private Pen _highlightBorderPen; private bool _ignoreHide; private bool _isDragging; private List<LegendBox> _legendBoxes; // for hit-testing private Rectangle _previousLine; private LegendBox _previousMouseDown; private Brush _selectionFontBrush; private Color _selectionFontColor; private Color _selectionHighlight; private TabColorDialog _tabColorDialog; private bool _wasDoubleClick; #endregion #region Constructors /// <summary> /// Creates a new instance of Legend. /// </summary> public Legend() { RootNodes = new List<ILegendItem>(); _icoChecked = Images.Checked; _icoUnchecked = Images.Unchecked; _contextMenu = new ContextMenu(); _selection = new HashSet<ILegendItem>(); _editBox = new TextBox { Parent = this, Visible = false }; _editBox.LostFocus += EditBoxLostFocus; Indentation = 30; _legendBoxes = new List<LegendBox>(); base.BackColor = Color.White; SelectionFontColor = Color.Black; SelectionHighlight = Color.FromArgb(215, 238, 252); // Adding a legend ensures that symbology dialogs will be properly launched. // Otherwise, an ordinary map may not even need them. SharedEventHandlers = new SymbologyEventManager { Owner = FindForm() }; } private void TabColorDialogChangesApplied(object sender, EventArgs e) { _editCategory.LowColor = _tabColorDialog.StartColor; _editCategory.HighColor = _tabColorDialog.EndColor; ILegendItem test = _editCategory.GetParentItem(); IRasterLayer rl = test as IRasterLayer; if (rl != null) { rl.WriteBitmap(); } } private void EditBoxLostFocus(object sender, EventArgs e) { HideEditBox(); } private void HideEditBox() { if (_editBox.Visible && _ignoreHide == false) { _ignoreHide = true; _previousMouseDown.Item.LegendText = _editBox.Text; _previousMouseDown = null; _editBox.Visible = false; _editBox.Text = string.Empty; _ignoreHide = false; RefreshNodes(); } } #endregion #region Methods /// <summary> /// Adds a map frame as a root node, and links an event handler to update /// when the mapframe triggers an ItemChanged event. /// </summary> /// <param name="mapFrame"></param> public void AddMapFrame(IFrame mapFrame) { mapFrame.IsSelected = true; if (!RootNodes.Contains(mapFrame)) { OnIncludeMapFrame(mapFrame); } RootNodes.Add(mapFrame); RefreshNodes(); } /// <summary> /// Removes the specified map frame if it is a root node. /// </summary> /// <param name="mapFrame"></param> /// <param name="preventRefresh">Boolean, if true, removing the map frame will not automatically force a refresh of the legend.</param> public void RemoveMapFrame(IFrame mapFrame, bool preventRefresh) { RootNodes.Remove(mapFrame); if (RootNodes.Contains(mapFrame) == false) OnExcludeMapFrame(mapFrame); if (preventRefresh) return; RefreshNodes(); } /// <summary> /// Given the current list of Maps or 3DMaps, it /// rebuilds the treeview nodes /// </summary> public void RefreshNodes() { // do any code that needs to happen if content changes _previousMouseDown = null; // to avoid memory leaks, because LegendBox contains reference to Layer IsInitialized = false; Invalidate(); } /// <summary> /// Un-selectes any selected items in the legend /// </summary> public void ClearSelection() { var list = _selection.ToList(); IFrame parentMap = null; if (list.Count > 0) { parentMap = list[0].ParentMapFrame(); if (parentMap != null) { parentMap.SuspendEvents(); } } foreach (var lb in list) { lb.IsSelected = false; } _selection.Clear(); if (parentMap != null) { parentMap.ResumeEvents(); } RefreshNodes(); } /// <summary> /// Occurs when linking the map frame /// </summary> /// <param name="mapFrame"></param> protected virtual void OnIncludeMapFrame(IFrame mapFrame) { mapFrame.ItemChanged += MapFrameItemChanged; mapFrame.LayerSelected += LayersLayerSelected; mapFrame.LayerRemoved += MapFrameOnLayerRemoved; } /// <summary> /// Occurs when we need to no longer listen to the map frame events /// </summary> /// <param name="mapFrame"></param> protected virtual void OnExcludeMapFrame(IFrame mapFrame) { mapFrame.ItemChanged -= MapFrameItemChanged; mapFrame.LayerSelected -= LayersLayerSelected; mapFrame.LayerRemoved -= MapFrameOnLayerRemoved; } private void MapFrameOnLayerRemoved(object sender, LayerEventArgs e) { _selection.Remove(e.Layer); } private void LayersLayerSelected(object sender, LayerSelectedEventArgs e) { if (e.IsSelected) { _selection.Add(e.Layer); } else { _selection.Remove(e.Layer); } } // a good selectionHighlight color: 215, 238, 252 private Brush HighlightBrush(Rectangle box) { float med = _selectionHighlight.GetBrightness(); float bright = med + 0.05f; if (bright > 1f) bright = 1f; float dark = med - 0.05f; if (dark < 0f) dark = 0f; Color brtCol = SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), bright); Color drkCol = SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), dark); return new LinearGradientBrush(box, brtCol, drkCol, LinearGradientMode.Vertical); } #endregion #region Properties /// <summary> /// Gets or sets the SharedEventHandler that is used for working with shared layer events. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public SymbologyEventManager SharedEventHandlers { get; set; } /// <summary> /// Gets or sets an integer representing how far child nodes are indented when compared to the parent nodes. /// </summary> [Category("Appearance"), Description("Gets or sets the indentation in pixels between a parent item and its children.")] public int Indentation { get; set; } /// <summary> /// This calculates a height for each item based on the height of the font. /// </summary> [Category("Appearance"), Description("Gets the height (which depends on the font) for each item.")] public int ItemHeight { get { if (Font.Height < 20) return 20; return Font.Height + 4; } } /// <summary> /// Gets or sets the selection font color /// </summary> [Category("Appearance"), Description("Specifies the color of the font in selected legend items.")] public Color SelectionFontColor { get { return _selectionFontColor; } set { _selectionFontColor = value; if (_selectionFontBrush != null) _selectionFontBrush.Dispose(); _selectionFontBrush = new SolidBrush(_selectionFontColor); IsInitialized = false; } } /// <summary> /// Specifies the principal color that a selected text box is highlighted with. /// </summary> [Category("Appearance"), Description("Specifies the color that a selected text box is highlighted with.")] public Color SelectionHighlight { get { return _selectionHighlight; } set { _selectionHighlight = value; if (_highlightBorderPen != null) _highlightBorderPen.Dispose(); float med = _selectionHighlight.GetBrightness(); float border = med - .25f; if (border < 0f) border = 0f; _highlightBorderPen = new Pen(SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), border)); } } /// <summary> /// Gets or sets the list of map frames being displayed by this legend. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<ILegendItem> RootNodes { get; set; } #endregion #region Protected Methods /// <summary> /// Gets or sets the progress handler for any progress messages like re-drawing images for rasters /// </summary> [Category("Controls"), Description("Gets or sets the progress handler for any progress messages like re-drawing images for rasters")] public IProgressHandler ProgressHandler { get; set; } /// <summary> /// /// </summary> /// <param name="e"></param> protected override void OnMouseDoubleClick(MouseEventArgs e) { _wasDoubleClick = true; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox lb in _legendBoxes) { if (!lb.Bounds.Contains(loc) || lb.CheckBox.Contains(loc)) continue; ILineCategory lc = lb.Item as ILineCategory; if (lc != null) { DetailedLineSymbolDialog lsDialog = new DetailedLineSymbolDialog(lc.Symbolizer); lsDialog.ShowDialog(); ILineSymbolizer sel = lc.Symbolizer.Copy(); sel.SetFillColor(Color.Cyan); lc.SelectionSymbolizer = sel; } IPointCategory pc = lb.Item as IPointCategory; if (pc != null) { DetailedPointSymbolDialog dlg = new DetailedPointSymbolDialog(pc.Symbolizer); dlg.ShowDialog(); IPointSymbolizer ps = pc.Symbolizer.Copy(); ps.SetFillColor(Color.Cyan); pc.SelectionSymbolizer = ps; } IPolygonCategory polyCat = lb.Item as IPolygonCategory; if (polyCat != null) { DetailedPolygonSymbolDialog dlg = new DetailedPolygonSymbolDialog(polyCat.Symbolizer); dlg.ShowDialog(); IPolygonSymbolizer ps = polyCat.Symbolizer.Copy(); ps.SetFillColor(Color.Cyan); ps.OutlineSymbolizer.SetFillColor(Color.DarkCyan); polyCat.SelectionSymbolizer = ps; } IFeatureLayer fl = lb.Item as IFeatureLayer; if (fl != null) { LayerDialog layDialog = new LayerDialog(fl, new FeatureCategoryControl()); layDialog.ShowDialog(); } IRasterLayer rl = lb.Item as IRasterLayer; if (rl != null) { LayerDialog dlg = new LayerDialog(rl, new RasterCategoryControl()); dlg.ShowDialog(); } IColorCategory cb = lb.Item as IColorCategory; if (cb != null) { _tabColorDialog = new TabColorDialog(); _tabColorDialog.ChangesApplied += TabColorDialogChangesApplied; _tabColorDialog.StartColor = cb.LowColor; _tabColorDialog.EndColor = cb.HighColor; _editCategory = cb; _tabColorDialog.ShowDialog(this); } } base.OnMouseDoubleClick(e); } /// <summary> /// Extends initialize to draw "non-selected" elements. /// </summary> /// <param name="e"></param> protected override void OnInitialize(PaintEventArgs e) { // draw standard background image to buffer base.OnInitialize(e); PointF topLeft = new Point(0, 0); if (RootNodes == null || RootNodes.Count == 0) return; _legendBoxes = new List<LegendBox>(); foreach (var item in RootNodes) { var args = new DrawLegendItemArgs(e.Graphics, item, ClientRectangle, topLeft); OnInitializeItem(args); topLeft.Y += SizeItem((int)topLeft.X, item, e.Graphics).Height; } } /// <summary> /// Overrides the drawing method to account for drawing lines /// when an item is being dragged to a new position. /// </summary> /// <param name="e">A PaintEventArgs</param> protected override void OnDraw(PaintEventArgs e) { //MessageBox.Show("OnDraw"); //Rectangle clip = e.ClipRectangle; //if (clip.IsEmpty || _isResizing) clip = ClientRectangle; //Bitmap stencil = new Bitmap(clip.Width, clip.Height, PixelFormat.Format32bppArgb); //Graphics g = Graphics.FromImage(stencil); //Brush b = new SolidBrush(BackColor); //g.FillRectangle(b, new Rectangle(0, 0, stencil.Width, stencil.Height)); //b.Dispose(); base.OnDraw(e); using (var pen = new Pen(BackColor)) { e.Graphics.DrawRectangle(pen, e.ClipRectangle); } if (_isDragging) { if (_previousLine.IsEmpty == false) { e.Graphics.DrawLine(Pens.Black, _previousLine.X, _previousLine.Y + 2, _previousLine.Right, _previousLine.Y + 2); } } } private void UpdateActions(ILegendItem mapLayer) { var manager = SharedEventHandlers; var layer = mapLayer as Layer; if (layer != null) { layer.LayerActions = manager == null ? null : manager.LayerActions; } var cc = mapLayer as ColorCategory; if (cc != null) { cc.ColorCategoryActions = manager == null ? null : manager.ColorCategoryActions; } var fl = mapLayer as FeatureLayer; if (fl != null) { fl.FeatureLayerActions = manager == null ? null : manager.FeatureLayerActions; } var il = mapLayer as ImageLayer; if (il != null) { il.ImageLayerActions = manager == null ? null : manager.ImageLayerActions; } var rl = mapLayer as RasterLayer; if (rl != null) { rl.RasterLayerActions = manager == null ? null : manager.RasterLayerActions; } } /// <summary> /// Draws the legend item from the DrawLegendItemArgs with all its child items. /// </summary> /// <param name="e">DrawLegendItemArgs that are needed to draw the legend item.</param> /// <returns>The position where the next LegendItem can be drawn.</returns> protected virtual PointF OnInitializeItem(DrawLegendItemArgs e) { if (e.Item.LegendItemVisible == false) return e.TopLeft; UpdateActions(e.Item); PointF topLeft = e.TopLeft; PointF tempTopLeft = topLeft; if (topLeft.Y > ControlRectangle.Bottom) { return topLeft; // drawing would be below the screen } if (topLeft.Y > ControlRectangle.Top - ItemHeight) { // Draw the item itself // Point tl = new Point((int)topLeft.X, (int)topLeft.Y); var itemBox = new LegendBox(); _legendBoxes.Add(itemBox); itemBox.Item = e.Item; itemBox.Bounds = new Rectangle(0, (int)topLeft.Y, Width, ItemHeight); itemBox.Indent = (int)topLeft.X / Indentation; DrawPlusMinus(e.Graphics, ref tempTopLeft, itemBox); int ih = ItemHeight; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > ih) tempTopLeft.Y += 3; } if (e.Item.LegendSymbolMode == SymbolMode.Symbol || e.Item.LegendSymbolMode == SymbolMode.GroupSymbol) { DrawSymbol(e.Graphics, ref tempTopLeft, itemBox); } if (e.Item.LegendSymbolMode == SymbolMode.Checkbox) { DrawCheckBoxes(e.Graphics, ref tempTopLeft, itemBox); } int width = (int)e.Graphics.MeasureString(e.Item.LegendText, Font).Width; int dY = 0; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > ih) dY = (s.Height - ih) / 2; tempTopLeft.Y += dY; } tempTopLeft.Y += (ih - Font.Height) / (float)2; itemBox.Textbox = new Rectangle((int)tempTopLeft.X, (int)topLeft.Y + dY, width, ItemHeight); if (itemBox.Item.IsSelected) { _selection.Add(itemBox.Item); Rectangle innerBox = itemBox.Textbox; innerBox.Inflate(-1, -1); using (var b = HighlightBrush(innerBox)) { e.Graphics.FillRectangle(b, innerBox); } SymbologyGlobal.DrawRoundedRectangle(e.Graphics, _highlightBorderPen, itemBox.Textbox); e.Graphics.DrawString(e.Item.LegendText, Font, _selectionFontBrush, tempTopLeft); } else { e.Graphics.DrawString(e.Item.LegendText, Font, Brushes.Black, tempTopLeft); } } int h = ItemHeight; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > h) h = s.Height + 6; } topLeft.Y += h; if (e.Item.IsExpanded) { topLeft.X += Indentation; if (e.Item.LegendItems != null) { List<ILegendItem> items = e.Item.LegendItems.ToList(); if (e.Item is IGroup) items.Reverse(); // reverse layers because of drawing order, don't bother reversing categories. foreach (var item in items) { var args = new DrawLegendItemArgs(e.Graphics, item, e.ClipRectangle, topLeft); topLeft = OnInitializeItem(args); if (topLeft.Y > ControlRectangle.Bottom) break; } } topLeft.X -= Indentation; } return topLeft; } /// <summary> /// Also hides the edit box so that it doesn't seem displaced from the item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnHorizontalScroll(object sender, ScrollEventArgs e) { HideEditBox(); base.OnHorizontalScroll(sender, e); } /// <summary> /// Also hides the edit box so that it doesn't seme displaced from the item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnVerticalScroll(object sender, ScrollEventArgs e) { HideEditBox(); base.OnVerticalScroll(sender, e); } /// <summary> /// Handles the case where the mouse down occurs. /// </summary> /// <param name="e">A MouseEventArgs</param> protected override void OnMouseDown(MouseEventArgs e) { HideEditBox(); if (_legendBoxes == null || _legendBoxes.Count == 0) return; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox box in _legendBoxes) { if (box.Bounds.Contains(loc)) { ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseDown(args); } } base.OnMouseDown(e); } /// <summary> /// Checks the Mouse Up event to see if it occurs inside a legend item. /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); if (!_wasDoubleClick) { foreach (LegendBox box in _legendBoxes) { if (!box.Bounds.Contains(loc)) continue; ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseUp(args); } } if (_isDragging && _dragItem != null) { if (_dragTarget != null && _dragTarget.Item != _dragItem.Item) { ILegendItem potentialParent = _dragTarget.Item.GetValidContainerFor(_dragItem.Item); if (potentialParent != null) { potentialParent.ParentMapFrame().SuspendEvents(); // The target must be a group, and the item must be a layer. ILayer lyr = _dragItem.Item as ILayer; if (lyr != null) { IGroup grp = _dragItem.Item.GetParentItem() as IGroup; lyr.LockDispose(); //when original location is inside group, remove layer from the group. if (grp != null) grp.Remove(lyr); int index = _dragTarget.Item.InsertIndex(_dragItem.Item); if (index == -1) index = 0; grp = potentialParent as IGroup; if (grp != null) { grp.Insert(index, lyr); //when the target is a group, assign the parent item. lyr.SetParentItem(grp); } lyr.UnlockDispose(); } potentialParent.ParentMapFrame().ResumeEvents(); OnOrderChanged(); potentialParent.ParentMapFrame().Invalidate(); } } Cursor = Cursors.Arrow; _isDragging = false; Invalidate(); } _wasDoubleClick = false; base.OnMouseUp(e); } /// <summary> /// Checks for checkbox changes and fires the ItemMouseUp event. /// </summary> /// <param name="e"></param> protected virtual void OnItemMouseUp(ItemMouseEventArgs e) { if (ItemMouseUp != null) ItemMouseUp(this, e); } /// <summary> /// Performs the default handling for mouse movememnt, and decides /// whether or not to fire an ItemMouseMove event. /// </summary> /// <param name="e">A MouseEventArgs</param> protected override void OnMouseMove(MouseEventArgs e) { if (_legendBoxes == null) return; bool cursorHandled = false; LegendBox currentBox = null; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox box in _legendBoxes) { if (box.Bounds.Contains(loc)) { currentBox = box; ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseMove(args); } } if (_isDragging) { _dragTarget = null; if (currentBox != null) _dragTarget = currentBox; if (ClientRectangle.Contains(e.Location)) { if (currentBox == null) _dragTarget = BottomBox; } if (_previousLine.IsEmpty == false) Invalidate(_previousLine); _previousLine = Rectangle.Empty; if (_dragTarget != null && _dragItem != null && _dragTarget != _dragItem) { LegendBox boxOverLine; int left = 0; LegendBox container = BoxFromItem(_dragTarget.Item.GetValidContainerFor(_dragItem.Item)); if (container != null) { left = (container.Indent + 1) * Indentation; } if (_dragTarget.Item.CanReceiveItem(_dragItem.Item)) { boxOverLine = _dragTarget; } else { boxOverLine = BoxFromItem(_dragTarget.Item.BottomMember()); } if (boxOverLine == null) { _previousLine = Rectangle.Empty; Cursor = Cursors.No; cursorHandled = true; } else { _previousLine = new Rectangle(left, boxOverLine.Bounds.Bottom, Width - left, 4); Cursor = Cursors.Hand; cursorHandled = true; Invalidate(_previousLine); } } if (cursorHandled == false) { Cursor = Cursors.No; cursorHandled = true; } } if (cursorHandled == false) { Cursor = Cursors.Arrow; } base.OnMouseMove(e); } /// <summary> /// The coordinates are in legend coordinates, but a LegendBox is provided to define the /// coordinates of the specified object. /// </summary> /// <param name="e">An ItemMouseEventArgs</param> protected virtual void OnItemMouseDown(ItemMouseEventArgs e) { if (ItemMouseDown != null) ItemMouseDown(this, e); } /// <summary> /// Fires the ItemMouseMove Event, which handles the mouse moving over one of the legend items. /// </summary> /// <param name="e">An ItemMouseEventArgs</param> protected virtual void OnItemMouseMove(ItemMouseEventArgs e) { if (ItemMouseMove != null) ItemMouseMove(this, e); } /// <summary> /// Fires the OrderChanged Event /// </summary> protected virtual void OnOrderChanged() { var h = OrderChanged; if (h != null) h(this, EventArgs.Empty); } #endregion #region Private Methods /// <summary> /// Retrieves the bottom box in the legend /// </summary> private LegendBox BottomBox { get { return _legendBoxes[_legendBoxes.Count - 1]; } } private void DoItemMouseMove(ItemMouseEventArgs e) { OnItemMouseMove(e); } private void DoItemMouseUp(ItemMouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); if (e.Button == MouseButtons.Left) { if (e.ItemBox.Item.LegendSymbolMode == SymbolMode.Checkbox) { if (e.ItemBox.CheckBox.Contains(loc)) { IRenderableLegendItem rendItem = e.ItemBox.Item as IRenderableLegendItem; if (rendItem != null) { // force a re-draw in the case where we are talking about layers. rendItem.IsVisible = !rendItem.IsVisible; } else { e.ItemBox.Item.Checked = !e.ItemBox.Item.Checked; } if (CheckBoxMouseUp != null) CheckBoxMouseUp(this, e); RefreshNodes(); } } if (e.ItemBox.Textbox.Contains(loc)) { if (e.ItemBox == _previousMouseDown) { _isDragging = false; // Edit via text box _editBox.Left = e.ItemBox.Textbox.Left; _editBox.Width = e.ItemBox.Textbox.Width + 10; _editBox.Top = e.ItemBox.Bounds.Top; _editBox.Height = e.ItemBox.Bounds.Height; _editBox.SelectedText = e.ItemBox.Item.LegendText; _editBox.Font = Font; _editBox.Visible = true; } } } if (e.Button == MouseButtons.Right) { if (e.ItemBox.Item.ContextMenuItems == null) return; _contextMenu.MenuItems.Clear(); foreach (SymbologyMenuItem mi in e.ItemBox.Item.ContextMenuItems) { AddMenuItem(_contextMenu.MenuItems, mi); } _contextMenu.Show(this, e.Location); _contextMenu.MenuItems.Clear(); } } /// <summary> /// Recursive add method to handle nesting of menu items. /// </summary> /// <param name="parent"></param> /// <param name="mi"></param> private static void AddMenuItem(Menu.MenuItemCollection parent, SymbologyMenuItem mi) { MenuItem m; if (mi.Icon != null) { m = new IconMenuItem(mi.Name, mi.Icon, mi.ClickHandler); } else if (mi.Image != null) { m = new IconMenuItem(mi.Name, mi.Image, mi.ClickHandler); } else { m = new IconMenuItem(mi.Name, mi.ClickHandler); } parent.Add(m); foreach (SymbologyMenuItem child in mi.MenuItems) { AddMenuItem(m.MenuItems, child); } } private void DoItemMouseDown(ItemMouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); // Toggle expansion if (e.ItemBox.ExpandBox.Contains(loc)) { e.ItemBox.Item.IsExpanded = !e.ItemBox.Item.IsExpanded; if (ExpandBoxMouseDown != null) ExpandBoxMouseDown(this, e); ResetLegend(); return; } if (e.ItemBox.Item.IsSelected) { // if we are already selected, prepare to edit in textbox _previousMouseDown = e.ItemBox; // Start dragging if (e.Button == MouseButtons.Left) { _isDragging = true; ILegendItem li = e.ItemBox.Item; while (li != null && !(li is ILayer)) { li = li.GetParentItem(); } ILayer lyr = li as ILayer; if (lyr != null && !RootNodes.Contains(lyr)) // don't allow to drag root nodes { _dragItem = BoxFromItem(lyr); } else { _isDragging = false; } } } else { // Check for textbox clicking if (e.ItemBox.Textbox.Contains(loc)) { if (ModifierKeys != Keys.Shift) { ClearSelection(); } e.ItemBox.Item.IsSelected = true; } } } /// <summary> /// Draw the symbol for a particular item. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the symbol should be added to.</param> private void DrawSymbol(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; // Align symbols so that their right side is about 20 pixels left // of the top-left X, but allow up to 128x128 sized symbols Size s = item.GetLegendSymbolSize(); int h = s.Height; if (h < 1) h = 1; if (h > 128) h = 128; int w = s.Width; if (w < 1) w = 1; if (w > 128) w = 128; int tH = ItemHeight; int x = (int)topLeft.X + tH - w; int y = (int)topLeft.Y; if (tH > h) y += (tH - h) / 2; Rectangle box = new Rectangle(x, y, w, h); itemBox.SymbolBox = box; item.LegendSymbol_Painted(g, box); topLeft.X += tH + 6; } /// <summary> /// If the LegendBox doesn't contain a symbol draw the plus or minus visible for controlling expansion. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the +/- should be added to.</param> private void DrawPlusMinus(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; if (item == null) return; if (item.LegendSymbolMode == SymbolMode.Symbol) return; // don't allow symbols to expand Point tl = new Point((int)topLeft.X, (int)topLeft.Y); tl.Y += (ItemHeight - 8) / 2; tl.X += 3; Rectangle box = new Rectangle(tl.X, tl.Y, 8, 8); itemBox.ExpandBox = box; Point center = new Point(tl.X + 4, (int)topLeft.Y + ItemHeight / 2); g.FillRectangle(Brushes.White, box); g.DrawRectangle(Pens.Gray, box); if (item.IsExpanded) { g.DrawRectangle(Pens.Gray, box); } else if (item.LegendItems != null && item.LegendItems.Any()) { g.DrawLine(Pens.Black, center.X, center.Y - 2, center.X, center.Y + 2); } g.DrawLine(Pens.Black, center.X - 2, center.Y, center.X + 2, center.Y); topLeft.X += 13; } /// <summary> /// If the LegendBox contains a checkbox item draw the checkbox for an item. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the checkbox should be added to.</param> private void DrawCheckBoxes(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; if (item == null) return; if (item.LegendSymbolMode != SymbolMode.Checkbox) return; if (item.Checked) { int top = (int)topLeft.Y + (ItemHeight - _icoChecked.Height) / 2; int left = (int)topLeft.X + 6; g.DrawIcon(_icoChecked, left, top); Rectangle box = new Rectangle(left, top, _icoChecked.Width, _icoChecked.Height); itemBox.CheckBox = box; } else { int top = (int)topLeft.Y + (ItemHeight - _icoUnchecked.Height) / 2; int left = (int)topLeft.X + 6; g.DrawIcon(_icoUnchecked, left, top); Rectangle box = new Rectangle(left, top, _icoChecked.Width, _icoChecked.Height); itemBox.CheckBox = box; } topLeft.X += 22; } /// <summary> /// Checks all the legend items and calculates a "page" large enough to contain everything currently visible. /// </summary> private void SizePage() { int w = Width; int totalHeight = 0; using (var g = CreateGraphics()) { foreach (var li in RootNodes) { var itemSize = SizeItem(0, li, g); totalHeight += itemSize.Height; if (itemSize.Width > w) w = itemSize.Width; } } int h = totalHeight; DocumentRectangle = new Rectangle(0, 0, w, h); } private Size SizeItem(int offset, ILegendItem item, Graphics g) { if (item == null) return new Size(0, 0); int width = offset + 30 + (int)g.MeasureString(item.LegendText, Font).Width; int height = ItemHeight; if (item.LegendSymbolMode == SymbolMode.Symbol) { Size s = item.GetLegendSymbolSize(); if (s.Height > ItemHeight) height = s.Height; } if (item.IsExpanded) { if (item.LegendItems != null) { foreach (ILegendItem child in item.LegendItems) { Size cs = SizeItem(offset + Indentation, child, g); height += cs.Height; if (cs.Width > width) width = cs.Width; } } } return new Size(width, height); } /// <summary> /// This isn't the best way to catch this. Only items in view should trigger a refresh. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MapFrameItemChanged(object sender, EventArgs e) { ResetLegend(); } private void ResetLegend() { SizePage(); ResetScroll(); RefreshNodes(); } /// <summary> /// Given a legend item, it searches the list of LegendBoxes until it finds it. /// </summary> /// <param name="item">LegendItem to find.</param> /// <returns>LegendBox belonging to the item.</returns> private LegendBox BoxFromItem(ILegendItem item) { return _legendBoxes.FirstOrDefault(box => box.Item == item); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Web; using HttpServer.Authentication; using HttpServer.Exceptions; using HttpServer.HttpModules; using HttpServer.Sessions; namespace HttpServer.MVC.Controllers { /// <summary> /// A controller in the Model-View-Controller pattern. /// Derive this class and add method with one of the following signatures: /// "public string MethodName()" or "public void MyMethod()". /// /// The first should return a string with the response, the latter /// should use SendHeader and SendBody methods to handle the response. /// </summary> /// <remarks> /// Last segment of the path is always broken into the properties Id and RequestedType /// Although note that the RequestedType can also be empty if no file extension have /// been specified. A typical use of file extensions in controllers is to specify which type of /// format to return. /// </remarks> /// <example> /// <code> /// public class MyController : RequestController /// { /// public string Hello() /// { /// if (RequestedType == "xml") /// return "&lt;hello&gt;World&lt;hello&gt;"; /// else /// return "Hello " + Request.QueryString["user"].Value + ", welcome to my world"; /// } /// /// public void File() /// { /// Response.Headers.ContentType = "text/xml"; /// Response.SendHeader(); /// } /// } /// </code> /// </example> /// <seealso cref="ControllerNameAttribute"/> /// <seealso cref="AuthRequiredAttribute"/> /// <seealso cref="AuthenticationValidatorAttribute"/> public abstract class RequestController : HttpModule, ICloneable { private const string Html = "html"; private readonly LinkedList<MethodInfo> _beforeFilters = new LinkedList<MethodInfo>(); private readonly Dictionary<string, MethodInfo> _binaryMethods = new Dictionary<string, MethodInfo>(); private readonly Dictionary<string, int> _authMethods = new Dictionary<string, int>(); private readonly Dictionary<string, MethodInfo> _methods = new Dictionary<string, MethodInfo>(); private LinkedListNode<MethodInfo> _lastMiddleFilter; private MethodInfo _defaultMethod; private string _defaultMethodStr; private MethodInfo _authValidator; //used temp during method mapping. private string _id; private MethodInfo _method; /// <summary> /// create a new request controller /// </summary> /// <param name="controller">prototype to copy information from</param> protected RequestController(RequestController controller) { _beforeFilters = controller._beforeFilters; _binaryMethods = controller._binaryMethods; _authMethods = controller._authMethods; _methods = controller._methods; ControllerName = controller.ControllerName; _defaultMethod = controller._defaultMethod; _defaultMethodStr = controller._defaultMethodStr; _authValidator = controller._authValidator; } /// <summary> /// create a new controller /// </summary> protected RequestController() { MapMethods(); } /// <summary> /// object that was attached during http authentication process. /// </summary> /// <remarks> /// You can also assign this tag yourself if you are using regular /// http page login. /// </remarks> /// <seealso cref="AuthenticationModule"/> protected object AuthenticationTag { get { return Session[AuthenticationModule.AuthenticationTag]; } set { Session[AuthenticationModule.AuthenticationTag] = value; } } /// <summary> /// Name of this controller (class name without the "Controller" part) /// </summary> public string ControllerName { get; private set; } /// <summary> /// Specifies the method to use if no action have been specified. /// </summary> /// <exception cref="ArgumentException">If specified method do not exist.</exception> public string DefaultMethod { get { return _defaultMethodStr; } set { if (_methods.ContainsKey(value.ToLower())) { _defaultMethodStr = value.ToLower(); _defaultMethod = _methods[_defaultMethodStr]; } else if (_binaryMethods.ContainsKey(value.ToLower())) { _defaultMethodStr = value.ToLower(); _defaultMethod = _binaryMethods[_defaultMethodStr]; } else throw new ArgumentException("New DefaultMethod value is not a valid controller method."); } } /// <summary> /// Id is the third part of the URI path. /// </summary> /// <remarks> /// <para>Is extracted as in: /controllername/methodname/id/ /// </para> /// <para>string.Empty if not specified.</para> /// </remarks> /// <example></example> public string Id { get { return _id ?? string.Empty; } } /// <summary> /// Method currently being invoked. /// Always in lower case. /// </summary> public string MethodName { get; private set; } /// <summary> /// Request information (like Uri, form, query string etc) /// </summary> protected IHttpRequest Request { get; private set; } /// <summary> /// Extension if a filename was specified. /// </summary> public string RequestedExtension { get; private set; } /// <summary> /// Response information (that is going to be sent back to the browser/client) /// </summary> protected IHttpResponse Response { get; private set; } /// <summary> /// Session information, is stored between requests as long as the session cookie is valid. /// </summary> protected IHttpSession Session { get; private set; } /* protected virtual void AddAuthAttribute(string methodName, object attribute) { if (attribute.GetType() == typeof (AuthenticatorAttribute)) { AuthenticatorAttribute attrib = (AuthenticatorAttribute) attribute; try { MethodInfo mi = GetType().GetMethod(attrib.Method); if (methodName == ClassMethodName) _classCheckAuthMethod = mi; else _authMethods.Add(methodName, mi); } catch (AmbiguousMatchException err) { if (methodName == "class") throw new InvalidOperationException( "Failed to find Authenticator method for class " + GetType().Name, err); else throw new InvalidOperationException("Failed to find Authenticator method for " + GetType().Name + "." + methodName); } } else throw new ArgumentException("Attribute is not of type AuthenticatorAttribute"); } */ /// <summary> /// Method that determines if an Uri should be handled or not by the module /// </summary> /// <param name="request">Uri requested by the client.</param> /// <returns>true if module should handle the Uri.</returns> public virtual bool CanHandle(IHttpRequest request) { if (request.UriParts.Length <= 0) return false; // check if controller name is correct. uri segments adds a slash to the segments if (string.Compare(request.UriParts[0], ControllerName, true) != 0) return false; // check action if (request.UriParts.Length > 1) { string uriPart = request.UriParts[1]; int pos = uriPart.LastIndexOf('.'); if (pos != -1) uriPart = uriPart.Substring(0, pos); if (_methods.ContainsKey(uriPart) || _binaryMethods.ContainsKey(uriPart)) return true; } if (request.UriParts.Length == 1) return _defaultMethod != null; return false; } /// <summary> /// Determines which method to use. /// </summary> /// <param name="request">Requested resource</param> protected virtual MethodInfo GetMethod(IHttpRequest request) { // Check where the default met if (request.UriParts.Length <= 1) return _defaultMethod; string uriPart = request.UriParts[1]; int pos = uriPart.LastIndexOf('.'); if (pos != -1) { RequestedExtension = uriPart.Substring(pos + 1); uriPart = uriPart.Substring(0, pos); } if (_methods.ContainsKey(uriPart)) return _methods[uriPart]; return _binaryMethods.ContainsKey(uriPart) ? _binaryMethods[uriPart] : null; } /// <summary> /// Call all before filters /// </summary> /// <returns>true if a before filter wants to abort the processing.</returns> /// <exception cref="InternalServerException">Controller filter failure, please try again.</exception> private bool InvokeBeforeFilters() { try { foreach (MethodInfo info in _beforeFilters) if (!(bool) info.Invoke(this, null)) return true; return false; } catch (TargetInvocationException err) { #if DEBUG FieldInfo remoteStackTraceString = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); remoteStackTraceString.SetValue(err.InnerException, err.InnerException.StackTrace + Environment.NewLine); throw err.InnerException; #else throw new InternalServerException("Controller filter failure, please try again.", err); #endif } } /// <summary> /// Override this method to be able to process result /// returned by controller method. /// </summary> protected virtual void InvokeMethod() { try { InvokeMethodInternal(); } catch (Exception err) { OnUnhandledException(err); } } /// <summary> /// Override this method if you want to be able to /// handle unhanded exceptions /// </summary> /// <param name="err">thrown exception</param> /// <remarks>Don't "eat" exceptions derived from <see cref="Exceptions.HttpException"/> since /// they are handled by the framework,unless your are sure of what you are /// doing..</remarks> /// <exception cref="Exception"><c>Exception</c>.</exception> protected virtual void OnUnhandledException(Exception err) { throw err; } /// <exception cref="UnauthorizedException">Need to authenticate.</exception> /// <exception cref="InternalServerException">Controller failure, please try again.</exception> private void InvokeMethodInternal() { if (_authMethods.ContainsKey(MethodName)) { if (_authValidator != null) { if (_authValidator.GetParameters().Length == 1) { if (!(bool) _authValidator.Invoke(this, new object[] {_authMethods[MethodName]})) return; } // backwards compatible. else if (!(bool)_authValidator.Invoke(this, null)) throw new UnauthorizedException("Need to authenticate."); } } if (_method.ReturnType == typeof (string)) { try { string temp = (string) _method.Invoke(this, null); if (temp != null) { TextWriter writer = new StreamWriter(Response.Body); writer.Write(temp); writer.Flush(); } } catch (TargetInvocationException err) { #if DEBUG FieldInfo remoteStackTraceString = typeof (Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); remoteStackTraceString.SetValue(err.InnerException, err.InnerException.StackTrace + Environment.NewLine); throw err.InnerException; #else throw new InternalServerException("Controller failure, please try again.", err); #endif } } else { _method.Invoke(this, null); } } /* /// <summary> /// check authentication attributes for the class /// </summary> protected virtual void MapClassAuth() { object[] attributes = GetType().GetCustomAttributes(true); foreach (object attribute in attributes) { if (attribute.GetType() == typeof (AuthenticatorAttribute)) AddAuthAttribute(ClassMethodName, attribute); if (attribute.GetType() == typeof (AuthenticationRequiredAttribute)) AddCheckAuthAttribute(ClassMethodName, attribute); } } */ /// <summary> /// This method goes through all methods in the controller and /// adds them to a dictionary. They are later used to invoke /// the correct method depending on the Uri. /// </summary> /// <exception cref="InvalidOperationException">Authentication validator have already been specified.</exception> private void MapMethods() { lock (_methods) { // already mapped. if (_methods.Count > 0) return; object[] controllerNameAttrs = GetType().GetCustomAttributes(typeof (ControllerNameAttribute), false); if (controllerNameAttrs.Length > 0) ControllerName = ((ControllerNameAttribute)controllerNameAttrs[0]).Name; else { ControllerName = GetType().Name; if (ControllerName.Contains("Controller")) ControllerName = ControllerName.Replace("Controller", ""); ControllerName = ControllerName.ToLower(); } MethodInfo[] methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance); foreach (MethodInfo info in methods) { ParameterInfo[] parameters = info.GetParameters(); // find regular render methods if (parameters.Length == 0 && info.ReturnType == typeof (string)) { string name = info.Name.ToLower(); if (name.Length > 3 && (name.Substring(0, 4) == "get_" || name.Substring(0, 4) == "set_")) continue; if (name == "tostring") continue; // Add authenticators object[] authAttributes = info.GetCustomAttributes(true); foreach (object attribute in authAttributes) if (attribute.GetType() == typeof (AuthRequiredAttribute)) _authMethods.Add(info.Name.ToLower(), ((AuthRequiredAttribute)attribute).Level); _methods.Add(info.Name.ToLower(), info); } // find raw handlers object[] attributes = info.GetCustomAttributes(typeof (RawHandlerAttribute), true); if (attributes.Length >= 1 && info.ReturnType == typeof (void) && parameters.Length == 0) { // Add authenticators object[] authAttributes = info.GetCustomAttributes(true); foreach (object attribute in authAttributes) if (attribute.GetType() == typeof(AuthRequiredAttribute)) _authMethods.Add(info.Name.ToLower(), ((AuthRequiredAttribute)attribute).Level); _binaryMethods.Add(info.Name.ToLower(), info); } } //foreach methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic); foreach (MethodInfo info in methods) { ParameterInfo[] parameters = info.GetParameters(); // find before filters. if (parameters.Length != 0 || info.ReturnType != typeof (bool)) continue; object[] authAttributes = info.GetCustomAttributes(true); foreach (object attribute in authAttributes) { if (attribute.GetType() == typeof (AuthenticationValidatorAttribute)) { if (_authValidator != null) throw new InvalidOperationException("Authentication validator have already been specified."); _authValidator = info; } else if (attribute.GetType() == typeof (BeforeFilterAttribute)) { BeforeFilterAttribute attr = (BeforeFilterAttribute) attribute; LinkedListNode<MethodInfo> node = new LinkedListNode<MethodInfo>(info); switch (attr.Position) { case FilterPosition.First: _beforeFilters.AddFirst(node); break; case FilterPosition.Last: _beforeFilters.AddLast(node); break; default: if (_lastMiddleFilter == null) _beforeFilters.AddLast(node); else _beforeFilters.AddAfter(_lastMiddleFilter, node); _lastMiddleFilter = node; break; } } } } // Map index method. MethodInfo mi = GetType().GetMethod("Index", BindingFlags.Public | BindingFlags.Instance); if (mi != null && mi.ReturnType == typeof(string) && mi.GetParameters().Length == 0) DefaultMethod = "Index"; } } /// <summary> /// Method that process the Uri /// </summary> /// <param name="request">Uses Uri and QueryString to determine method.</param> /// <param name="response">Relays response object to invoked method.</param> /// <param name="session">Relays session object to invoked method. </param> public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session) { if (!CanHandle(request)) return false; SetupRequest(request, response, session); if (InvokeBeforeFilters()) return true; InvokeMethod(); return true; } /// <summary> /// Will assign all variables that are unique for each session /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <param name="session"></param> /// <exception cref="NotFoundException">No default method is specified.</exception> protected virtual void SetupRequest(IHttpRequest request, IHttpResponse response, IHttpSession session) { RequestedExtension = Html; // extract id if (request.Uri.Segments.Length > 3) { _id = request.Uri.Segments[3]; if (_id.EndsWith("/")) _id = _id.Substring(0, _id.Length - 1); else { int pos = _id.LastIndexOf('.'); if (pos != -1) { RequestedExtension = _id.Substring(pos + 1); _id = _id.Substring(0, pos); } } _id = HttpUtility.UrlDecode(_id); } else if (request.QueryString["id"] != HttpInputItem.Empty) _id = HttpUtility.UrlDecode(request.QueryString["id"].Value); else _id = string.Empty; Request = request; Response = response; Session = session; if (request.Uri.Segments.Length == 2 && _defaultMethod == null) throw new NotFoundException("No default method is specified."); _method = GetMethod(request); if (_method == null) throw new NotFoundException("Requested action could not be found."); MethodName = _method.Name.ToLower(); } #region ICloneable Members /// <summary> /// Make a clone of this controller /// </summary> /// <returns>a new controller with the same base information as this one.</returns> public abstract object Clone(); #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NDesk.Options; using GitTfs.Core; using GitTfs.Util; using StructureMap; namespace GitTfs.Commands { [Pluggable("rcheckin")] [RequiresValidGitRepository] public class Rcheckin : GitTfsCommand { private readonly CheckinOptions _checkinOptions; private readonly CheckinOptionsFactory _checkinOptionsFactory; private readonly TfsWriter _writer; private readonly Globals _globals; private readonly AuthorsFile _authors; private bool AutoRebase { get; set; } private bool ForceCheckin { get; set; } public Rcheckin(CheckinOptions checkinOptions, TfsWriter writer, Globals globals, AuthorsFile authors) { _checkinOptions = checkinOptions; _checkinOptionsFactory = new CheckinOptionsFactory(globals); _writer = writer; _globals = globals; _authors = authors; } public OptionSet OptionSet { get { return new OptionSet { {"a|autorebase", "Continue and rebase if new TFS changesets found", v => AutoRebase = v != null}, {"ignore-merge", "Force check in ignoring parent tfs branches in merge commits", v => ForceCheckin = v != null}, }.Merge(_checkinOptions.OptionSet); } } // uses rebase and works only with HEAD public int Run() { _globals.WarnOnGitVersion(); if (_globals.Repository.IsBare) throw new GitTfsException("error: you should specify the local branch to checkin for a bare repository."); return _writer.Write("HEAD", PerformRCheckin); } // uses rebase and works only with HEAD in a none bare repository public int Run(string localBranch) { _globals.WarnOnGitVersion(); if (!_globals.Repository.IsBare) throw new GitTfsException("error: This syntax with one parameter is only allowed in bare repository."); _authors.LoadAuthorsFromSavedFile(_globals.GitDir); return _writer.Write(GitRepository.ShortToLocalName(localBranch), PerformRCheckin); } private int PerformRCheckin(TfsChangesetInfo parentChangeset, string refToCheckin) { if (_globals.Repository.IsBare) AutoRebase = false; if (_globals.Repository.WorkingCopyHasUnstagedOrUncommitedChanges) { throw new GitTfsException("error: You have local changes; rebase-workflow checkin only possible with clean working directory.") .WithRecommendation("Try 'git stash' to stash your local changes and checkin again."); } // get latest changes from TFS to minimize possibility of late conflict Trace.TraceInformation("Fetching changes from TFS to minimize possibility of late conflict..."); parentChangeset.Remote.Fetch(); if (parentChangeset.ChangesetId != parentChangeset.Remote.MaxChangesetId) { if (AutoRebase) { _globals.Repository.CommandNoisy("rebase", "--rebase-merges", parentChangeset.Remote.RemoteRef); parentChangeset = _globals.Repository.GetTfsCommit(parentChangeset.Remote.MaxCommitHash); } else { if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, parentChangeset.Remote.MaxCommitHash); throw new GitTfsException("error: New TFS changesets were found.") .WithRecommendation("Try to rebase HEAD onto latest TFS checkin and repeat rcheckin or alternatively checkins"); } } IEnumerable<GitCommit> commitsToCheckin = _globals.Repository.FindParentCommits(refToCheckin, parentChangeset.Remote.MaxCommitHash); Trace.WriteLine("Commit to checkin count:" + commitsToCheckin.Count()); if (!commitsToCheckin.Any()) throw new GitTfsException("error: latest TFS commit should be parent of commits being checked in"); SetupMetadataExport(parentChangeset.Remote); return _PerformRCheckinQuick(parentChangeset, refToCheckin, commitsToCheckin); } private void SetupMetadataExport(IGitTfsRemote remote) { var exportInitializer = new ExportMetadatasInitializer(_globals); var shouldExport = _globals.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true"; exportInitializer.InitializeRemote(remote, shouldExport); } private int _PerformRCheckinQuick(TfsChangesetInfo parentChangeset, string refToCheckin, IEnumerable<GitCommit> commitsToCheckin) { var tfsRemote = parentChangeset.Remote; string currentParent = parentChangeset.Remote.MaxCommitHash; int newChangesetId = 0; foreach (var commit in commitsToCheckin) { var message = BuildCommitMessage(commit, !_checkinOptions.NoGenerateCheckinComment, currentParent); string target = commit.Sha; var parents = commit.Parents.Where(c => c.Sha != currentParent).ToArray(); string tfsRepositoryPathOfMergedBranch = _checkinOptions.NoMerge ? null : FindTfsRepositoryPathOfMergedBranch(tfsRemote, parents, target); var commitSpecificCheckinOptions = _checkinOptionsFactory.BuildCommitSpecificCheckinOptions(_checkinOptions, message, commit, _authors); Trace.TraceInformation("Starting checkin of {0} '{1}'", target.Substring(0, 8), commitSpecificCheckinOptions.CheckinComment); try { newChangesetId = tfsRemote.Checkin(target, currentParent, parentChangeset, commitSpecificCheckinOptions, tfsRepositoryPathOfMergedBranch); var fetchResult = tfsRemote.FetchWithMerge(newChangesetId, false, parents.Select(c => c.Sha).ToArray()); if (fetchResult.NewChangesetCount != 1) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, target); if (AutoRebase) tfsRemote.Repository.CommandNoisy("rebase", "--rebase-merges", tfsRemote.RemoteRef); else throw new GitTfsException("error: New TFS changesets were found. Rcheckin was not finished."); } currentParent = target; parentChangeset = new TfsChangesetInfo { ChangesetId = newChangesetId, GitCommit = tfsRemote.MaxCommitHash, Remote = tfsRemote }; Trace.TraceInformation("Done with {0}.", target); } catch (Exception) { if (newChangesetId != 0) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, currentParent); } throw; } } if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, tfsRemote.MaxCommitHash); else _globals.Repository.ResetHard(tfsRemote.MaxCommitHash); Trace.TraceInformation("No more to rcheckin."); Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); return GitTfsExitCodes.OK; } public string BuildCommitMessage(GitCommit commit, bool generateCheckinComment, string latest) { return generateCheckinComment ? _globals.Repository.GetCommitMessage(commit.Sha, latest) : _globals.Repository.GetCommit(commit.Sha).Message; } private string FindTfsRepositoryPathOfMergedBranch(IGitTfsRemote remoteToCheckin, GitCommit[] gitParents, string target) { if (gitParents.Length != 0) { Trace.TraceInformation("Working on the merge commit: " + target); if (gitParents.Length > 1) Trace.TraceWarning("warning: only 1 parent is supported by TFS for a merge changeset. The other parents won't be materialized in the TFS merge!"); foreach (var gitParent in gitParents) { var tfsCommit = _globals.Repository.GetTfsCommit(gitParent); if (tfsCommit != null) return tfsCommit.Remote.TfsRepositoryPath; var lastCheckinCommit = _globals.Repository.GetLastParentTfsCommits(gitParent.Sha).FirstOrDefault(); if (lastCheckinCommit != null) { if (!ForceCheckin && lastCheckinCommit.Remote.Id != remoteToCheckin.Id) throw new GitTfsException("error: the merged branch '" + lastCheckinCommit.Remote.Id + "' is a TFS tracked branch (" + lastCheckinCommit.Remote.TfsRepositoryPath + ") with some commits not checked in.\nIn this case, the local merge won't be materialized as a merge in tfs...") .WithRecommendation("check in all the commits of the tfs merged branch in TFS before trying to check in a merge commit", "use --ignore-merge option to ignore merged TFS branch and check in commit as a normal changeset (not a merge)."); } else { Trace.TraceWarning("warning: the parent " + gitParent + " does not belong to a TFS tracked branch (not checked in TFS) and will be ignored!"); } } } return null; } public void RebaseOnto(string newBaseCommit, string oldBaseCommit) { _globals.Repository.CommandNoisy("rebase", "--rebase-merges", "--onto", newBaseCommit, oldBaseCommit); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Base data reader class to read external data into the framework /// </summary> public class OTDataReader : Object { public delegate void DataReaderDelegate(OTDataReader reader); protected bool _available = false; /// <summary> /// This delegate is executed when the data becomes available /// </summary> public DataReaderDelegate onDataAvailable = null; /// <summary> /// If true, readers will stay open /// </summary> /// <remarks> /// When you are keeping the readers and register a new reader using OTDataReader.Register(newReader) and the new reader has the same id as /// one that is already available the reader will re-use that already available reader. /// </remarks> static bool keepReaders = false; static List<OTDataReader> all = new List<OTDataReader>(); static Dictionary<string, OTDataReader>lookup = new Dictionary<string, OTDataReader>(); /// <summary> /// Registeres the specified newReader. /// </summary> /// <remarks> /// When OTDataReader.keepReaders is true and you are registering a new reader using OTDataReader.Register(newReader) and the new reader has /// the same id as one that is already available the reader will re-use that already available reader. /// </remarks> public static OTDataReader Register(OTDataReader newReader) { string id = newReader.id; if (lookup.ContainsKey(id) && !keepReaders) lookup[id].Close(); if (!lookup.ContainsKey(id)) { all.Add(newReader); lookup.Add(id,newReader); } return lookup[id]; } protected void Available() { _available = true; if (onDataAvailable!=null) onDataAvailable(this); } string _id; /// <summary> /// Gets the id of this reader /// </summary> public string id { get { return _id; } } /// <summary> /// Closes all readers /// </summary> static public void CloseAll() { while (all.Count>0) { if (all[0].available) all[0].Close(); else all.RemoveAt(0); } all.Clear(); } /// <summary> /// True if the reader is opened and available /// </summary> public bool available { get { return _available; } } /// <summary> /// Opens the reader /// </summary> public virtual bool Open() { _row = 0; _available = false; datasetRows.Clear(); return _available; } /// <summary> /// Closes the reader /// </summary> public virtual void Close() { if (lookup.ContainsKey(id)) lookup.Remove(id); if (all.Contains(this)) all.Remove(this); } public OTDataReader(string id) { this._id = id; } protected virtual int LoadDataSet(string dataId, string dataset) { return 0; } Dictionary<string , int> datasetRows = new Dictionary<string, int>(); /// <summary> /// Loads a dataset /// </summary> /// <remarks> /// This first row of this dataset becomes the active dataset row /// </remarks> public void DataSet(string dataset, string datasource) { dataset = dataset.ToLower(); int _rows = LoadDataSet(dataset, datasource); if (_rows>0) { datasetRows.Add(dataset,_rows); _dataset = dataset; _row = 0; } return; } string _dataset = ""; /// <summary> /// Gets or sets the active dataset. /// </summary> public string dataset { get { return _dataset; } set { string v = value.ToLower(); if (datasetRows.ContainsKey(v)) _dataset = v; else _dataset = ""; } } /// <summary> /// Gets or sets the active row of the current dataset /// </summary> public int rowCount { get { if (dataset == "") throw new System.Exception("No dataset active!"); return datasetRows[dataset]; } } int _row = 0; /// <summary> /// Gets or sets the active row of the current dataset /// </summary> public int row { get { if (dataset == "") throw new System.Exception("No dataset active!"); return _row; } set { if (dataset == "") throw new System.Exception("No dataset active!"); if (value<0 || value>=datasetRows[dataset]) throw new System.Exception("Invalid dataset row!"); else { _row = value; _bof = false; _eof = false; } } } /// <summary> /// To first row of current dataset /// </summary> public void First() { _bof = false; _eof = false; row = 0; } /// <summary> /// To last row of current dataset /// </summary> public void Last() { _bof = false; _eof = false; row = rowCount-1; } /// <summary> /// To previous row of current dataset /// </summary> public void Previous() { if (row>1) row--; else { _bof = true; _row = 0; } } /// <summary> /// To next row of current dataset /// </summary> public void Next() { if (row<rowCount-1) row++; else { _eof = true; _row = rowCount-1; } } bool _eof = false; /// <summary> /// True if we got to the last row of the dataset /// </summary> public bool EOF { get { return _eof; } } bool _bof = false; /// <summary> /// True if we got to the first row of the dataset /// </summary> public bool BOF { get { return _bof; } } protected virtual object GetData(string variable) { return null; } object Data(string variable) { if (_dataset == "") throw new System.Exception("No dataset active!"); return GetData(variable); } /// <summary> /// Gets data as a string from the reader /// </summary> public string StringData(string variable) { try { return System.Convert.ToString(Data(variable)); } catch(System.Exception) { return ""; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public int IntData(string variable) { try { return System.Convert.ToInt32(Data(variable)); } catch(System.Exception) { return 0; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public float FloatData(string variable) { try { return System.Convert.ToSingle(Data(variable)); } catch(System.Exception) { return 0.0f; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public bool BoolData(string variable) { try { return System.Convert.ToBoolean(Data(variable)); } catch(System.Exception) { return false; } } } public class OTDataSet { }